Angular ViewChild 方法调用期间绑定属性不可用
Angular bound properties not available during ViewChild method call
我有一个 Angular2 视图,它在视图加载期间调用子组件上的方法来初始化它。子组件绑定到我想在方法调用期间访问的父组件上的 属性;但是,出于某种原因,它直到调用完成后才被填充。 This plunker 演示了这个问题。
export class ParentComponent implements OnInit {
@ViewChild('child')
child: ChildComponent;
message: string;
ngOnInit() {
this.message = "Set by parent";
this.child.onParentInvoke();
}
}
export class ChildComponent implements OnInit {
@Input()
message: string;
callProperty: string;
onParentInvoke() {
//I want the message property to be populated here
this.callProperty = this.message;
}
ngOnInit() {
}
}
父模板:
<div>This is parent</div>
<div>Message: {{message}}</div>
<child #child [message]="message"></child>
子模板:
<div>This is child</div>
<div>Message during method call: {{callProperty}}</div>
<div>Message: {{message}}</div>
谁能告诉我为什么 属性 在这个阶段没有绑定,我可以做些什么来确保它在方法调用期间被填充?
编辑:Paul Taylor 评论后的解决方案:
export class ParentComponent implements OnInit {
@ViewChild('child')
child: ChildComponent;
message: string;
constructor(
private ref: ChangeDetectorRef,
) { }
ngOnInit() {
this.message = "Set by parent";
this.ref.detectChanges();
this.child.onParentInvoke();
}
}
我有一个 Angular2 视图,它在视图加载期间调用子组件上的方法来初始化它。子组件绑定到我想在方法调用期间访问的父组件上的 属性;但是,出于某种原因,它直到调用完成后才被填充。 This plunker 演示了这个问题。
export class ParentComponent implements OnInit {
@ViewChild('child')
child: ChildComponent;
message: string;
ngOnInit() {
this.message = "Set by parent";
this.child.onParentInvoke();
}
}
export class ChildComponent implements OnInit {
@Input()
message: string;
callProperty: string;
onParentInvoke() {
//I want the message property to be populated here
this.callProperty = this.message;
}
ngOnInit() {
}
}
父模板:
<div>This is parent</div>
<div>Message: {{message}}</div>
<child #child [message]="message"></child>
子模板:
<div>This is child</div>
<div>Message during method call: {{callProperty}}</div>
<div>Message: {{message}}</div>
谁能告诉我为什么 属性 在这个阶段没有绑定,我可以做些什么来确保它在方法调用期间被填充?
编辑:Paul Taylor 评论后的解决方案:
export class ParentComponent implements OnInit {
@ViewChild('child')
child: ChildComponent;
message: string;
constructor(
private ref: ChangeDetectorRef,
) { }
ngOnInit() {
this.message = "Set by parent";
this.ref.detectChanges();
this.child.onParentInvoke();
}
}