I have a child component that is used twice within its parent, it uses ngOnChages to update values;
This all worked fine, but now I'm trying to manipulate the template, within the child, according to information passed it via @Input variables.
What I'm finding is; when the parent component is first loaded, the template variables are undefined, within a function call
This makes sense because this function is called within the onChanges method and does not give the template enough time to load.
I need to refactor my code, but how?
At the moment it works if I use setTimeout
So to simply:
@ViewChild('myContainer', {read: ElementRef}) myContainer: ElementRef;
@Input() myUpdatingVar
ngOnChanges(): void {
if (this.myUpdatingVar === someValue) {
this.myFunc(this.someValue1);
} else {
this.myFunc(this.someValue2);
}
}
myFunc(param){
do stuff....
this.updateDom(anotherParam);
}
updateDom(param) {
// If I use setTimeout this works
this.myContainer.nativeElement.querySelector(`#someId`); // Undefined
}
For DOM manipulation, you should use the
ngAfterViewInitlifecycle hook, to ensure the template has loaded into the DOM.ngOnChangesfires once early, even beforengOnInit. Far too early for DOM manipulation.You can use an
isViewInitializedBoolean and set it to true inngAfterViewInit, and then use it in anifcondition inngOnChanges.