Angular 10 - Enable ViewChild to get instance regardless of static property

801 Views Asked by At

Are there some ways for @ViewChild decorator to get the child component's instance in ngOnInit as the same from the old @ViewChild of angular 6?

I tried something like:

@Component({
  ....
})
export class AppComponent implements OnInit {
  @ViewChild(HelloComponent, {static: true})
  @ViewChild(HelloComponent, {static: false})
  hello: HelloComponent;

  ngOnInit() {
      console.log('Hello Instance',this.hello);
  }
}

but it causes me error saying Multiple decorators are not allowed for the same member

1

There are 1 best solutions below

0
On

I'd like to share what I just discovered for @ViewChild for other readers knowledge

to let @ViewChild with static property set to false in ngOnInit

I have to put it inside setTimeout() like so:

@ViewChild(HelloComponent, {static:false}) hello: HelloComponent;

ngOnInit() {
    setTimeout(() => {
        console.log('Hello Instance',this.hello);
    }, 100);
}

this way, it can get the child component inside ngOnInit