使用 Angular 6。我有一个页面,其中包含约2个子组件。第一个组件有2个输入框,第二个组件有一个下拉菜单。我的父组件只有按钮点击事件。
我知道我可以在子组件上使用 Eventemitter 并将值传递给我的父组件,但如果没有按钮点击事件,我该如何从子组件传递值。我尝试使用 ViewChild,但存在一定的延迟,直到视图完全加载。我以下面的方式使用 ViewChild:
-- 父级 --
我知道我可以在子组件上使用 Eventemitter 并将值传递给我的父组件,但如果没有按钮点击事件,我该如何从子组件传递值。我尝试使用 ViewChild,但存在一定的延迟,直到视图完全加载。我以下面的方式使用 ViewChild:
-- 父级 --
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";
@Component({
selector: 'app-parent',
template: `
Message: {{ message }}
<app-child></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child;
constructor() { }
message:string;
ngAfterViewInit() {
this.message = this.child.message
}
}
--Child--
import { Component} from '@angular/core';
@Component({
selector: 'app-child',
template: `
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message = 'Hola Mundo!';
constructor() { }
}
我从https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/中获取了上述例子。
请问有人能提供如何在不使用任何按钮点击/发射器的情况下实现从子组件传递/读取数据的输入?
--更新--
--子组件--
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'ct-child',
templateUrl: './child.html'
})
export class ChildComponent implements OnInit {
childmessage: string = "Child Message!"
constructor() { }
ngOnInit() {}
}
--家长--
import { Component, OnInit} from '@angular/core';
@Component({
selector: 'ct-parent',
templateUrl: './parent.html'
})
export class ParentComponent implements OnInit {
constructor() { }
message: string;
getDataFromChild(child1): void {
this.message = child1.message;
}
ngOnInit() {}
}
--父级HTML--
Message: {{message}}
<ct-child #child1></ct-metadata>
<button type="button" (click)="getDataFromChild(child1)">Click Me!</button>
我已按照评论中的方法尝试,但这并不起作用。