1

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>

P.S: 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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your ans @Chrillewoodz, can you please also explain why #typeAhead is not a reference here? Is it because it's of type NgbTypeahead?
@BijaySingh I assume that NgbTypeahead is a directive so it's a reference to the directive itself rather than the input element.
2

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 (e.g. it would never update after that point)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.