简体   繁体   中英

Multiple template reference variable in Angular

In one of my component's template input element I have created two different reference variables, something like this:

<input type="text" placeholder="..." #typeAhead="ngbTypeahead"
       #relationTypeInput>

PS: This is not the exact code, but my actual code is similar to this one

In the component ts file these variable are declared as follows:

@ViewChild('typeAhead') typeAhead: NgbTypeahead;
@ViewChild('relationTypeInput') relationTypeInput: ElementRef;

Then I am using the former one in ngOnInit() and the later one in ngAfterViewInit(). To my surprise I didn't got any error and it's working, but I don't understand how?

This is because #typeAhead isn't a reference to the element, in this case the input . This is why it's defined when ngOnInit runs, while #relationTypeInput is not.

In the later versions of Angular (v10+) you would need to use ngAfterViewInit

Up to v7, Angular stated that ngOnInit was not a reliable lifecycle hook from which to reference ViewChild properties, but it was common knowledge that it was reliable. In v8/9, you need to add an option {static: true} to the ViewChild to allow the property to be referenced in ngOnInit - but this had other affects on the property (eg it would never update after that point)

You can read more about it here https://angular.io/guide/static-query-migration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM