Search code examples
angularviewchild

@viewChild return undefined in Angular


I have already read other posts similar to mine, but they are not exactly related, so I ask for my specific case. When I try to take the value of child.message or print child in console I get a 'child is undefined' error.

app.component.ts

@Component({
  selector: 'app-root',
  template: `
    <h1>Example of uses of @ViewChild with child component</h1>
    <app-child-component></app-child-component>
    <p>This is the message value of the child component selected with @ViewChild: '{{childMessage}}' </p>
  `
})

export class AppComponent implements AfterViewInit{
  
    @ViewChild(ChildComponent, { read: true }) child!: ChildComponent

    childMessage:string
    
    ngAfterViewInit(){
        console.log(this.child)
        this.childMessage = this.child.message
    }

}

child.component.ts

@Component({
  selector: 'app-child-component',
  template: `
    <div class="container">
        <h2>This is the child component!</h2>
        <p> The message value is '{{message}}'</p>
    </div>
    `,
    styles: ['.container{ background-color: rgb(154, 218, 226); border: 1px solid black; }']
})
export class ChildComponent {

    message:string = 'Ave Caesar!'

}

I followed the official angular documentation, what's wrong? Thanks!


Solution

  • The read property is used to distinct several injectable items available (by the way it can't be set as a boolean). You don't need it in your use case. It will work by removing it.

    To avoid expression has changed after it was checked error, run the change detection manually :

    constructor(cdr: ChangeDetectorRef) {}
    
    ngAfterViewInit() {
        this.childMessage = this.child.message;
        this.cdr.detectChanges();
      }