Archive for December, 2020

December 24th, 2020
11:40 am
Angular changes DOM again after calling ngAfterViewInit

Posted under Angular & Web
Tags , ,

Originally I used ngAfterViewInit to perform some custom DOM changes in a component (adding a default title to certain dynamically added anchor tags).

Unfortunately this resulted in weird behaviour whereby the changes did not appear in the DOM. It appeared that the DOM was being rebuilt again after the lifecycle hook had been called, as initially in debug the changes could be seen on the page, then they instantly disappeared.

Switching to using ngAfterViewChecked resolved the problem, as noted in this StackOverflow post. Whilst there are efficiency issues to consider here, it is obviously essential that the lifecycle hook used is guaranteed to be called every time the DOM is updated. Note also that the first time through flag used in the above StackOverflow post did not work – clearly the DOM was still being changed after the first call to ngAfterViewChecked, so the first time through flag was dropped. This other StackOverflow post also discusses the same solution to the problem.

Comments Off on Angular changes DOM again after calling ngAfterViewInit