Reputation: 101
I have a parent component and use ViewChild to call the method in child component. However, when I load the data and use that method to pass data, It show the error my method is undefined. Where did I get it wrong?
Flow: At first: After NgOnInit() method, I load the data and pass It to the child component Second try: I use NgAfterViewInit() to load the data end then pass it to the child component but it has the same error
Note: The parent has a variable that can create child component multiple times
Sample Code with further description:
Upvotes: 1
Views: 1342
Reputation: 5181
You can pass data to the child using the @Input
decorator. The theory:
input
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
}
Parent HTML :
<app-child [name]="name"></app-child>
Child TS:
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './app-child.component.html',
styleUrls: [ './app-child.component.css' ]
})
export class AppChildComponent {
@Input() name = '';
ngOnChanges(changes: SimpleChanges): void {
if (changes.name) {
this.setup();
}
}
setup() {
...
}
}
Inside setup of the child you can then handle the data as expected.
Upvotes: 3