1
votes

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:

1
Hi NguYen welcome to SO. Can you please include code as wellUmesh
Please replicate your example with stackblitz and post a link or add the content of yout parent/child ts files.Gérôme Grignon
Here it is: stackblitz.com/edit/angular-t917aq. The sample code is related to mine. And I have some description to make it clearerhai.nguyen
Please post this code example into your question for future reference. Other users who looks for the same problem might won't find your link later anymore. stackoverflow.com/help/minimal-reproducible-exampleLing Vu

1 Answers

3
votes

You can pass data to the child using the @Input decorator. The theory:

  1. Pass data through this input
  2. Fire change detection to handle those changes Parent TS:
@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.