I'm learning Angular 6, I tought I was doing it right, but I'm facing a "problem-doubt"
I have a parent and a Child:
- My parent is sharing info to my child by using input binding
- A button trigger a function where the info is updated
- Inmediatly, parent calls a child function via @ViewChild
A Stackblitz can be found here
My parent components looks like:
Html:
This is the parent
<child [data]="my_data"></child>
<button (click)="fireAll()">Fire All!</button>
Typescript:
export class AppComponent {
@ViewChild(ChildComponent) childComp: ChildComponent;
my_data = 'Nothing yet';
public fireAll(){
this.my_data = "I want to show this info in console";
this.childComp.writeToConsole();
//setTimeout(()=>this.childComp.writeToConsole(), 500); //This works well
}
}
Child:
export class ChildComponent {
@Input() data: string;
writeToConsole(){
console.log(this.data);
}
}
The problem is: The first time I click my button, I'm expecting to see in console "I want to show this info in console", instead of that I'm recieving "Nothing yet". But if I click it again, the expected result is reached. I suppose there is a delay between the parent pass data to child because if I use setTimeout to hold on a little, all works fine.
My questions:
- What is the best way to send data from parent to child and to use it inmediatly in child?
- What am I doing wrong?
Really appreciate your help, thanks