I have an Angular2 view that calls a method on a child component to initialise it during the view load. The child component is bound to a property on the parent that I want to access during the method call; however, for some reason, it is not populated until after the call is complete. This plunker demonstrates the issue.
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() {
}
}
Parent template:
<div>This is parent</div>
<div>Message: {{message}}</div>
<child #child [message]="message"></child>
Child template:
<div>This is child</div>
<div>Message during method call: {{callProperty}}</div>
<div>Message: {{message}}</div>
Can anyone tell me why the property is not bound at this stage, and what I can do to ensure that it is populated during the method call?
EDIT: Solution following Paul Taylor comment:
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();
}
}