We can easily access an element from HTML inside the ts file by using the ViewChild decorator in Angular. But, what if the element is inside an element with ngIf whose set to false initially and we may want to change it to true later.
When ngIf is set to false on an element and we load the component, that entire element and its children will not be present in the DOM, so we will not be able to get its or any of its children reference inside the DOM. When we change the value of ngIf to true later, Angular adds the required DOM content but do not re-run the entire component. So, if we try to use ViewChild normally here to access the element, it will we undefined even after changing the value of ngIf to true later.
To access the element which is inside an element with ngIf set to false, we can use a setter function and decorate it with ViewChild.
example:
Suppose we have a component with login and register forms. We want to display only one of them depending on a property. We want to access an element from the register form which is inside an element containing *ngIf directive which is set to false initially and set its place holder value from the component ts file.
HTML:
ts file:
Few developers use another work around to solve this problem by hiding the element they want to access inside the ts file instead of using ngIf. With this approach we can use ViewChild normally since the element we want to access will always be there in the DOM but only hidden based on some condition.
Leave A Comment