If I have the following:
<div *ngIf="user$ | async as user" class="container">
<p>user.name</p>
</div>
Is there a way I can execute code when the div
above finally appears on screen?
If I have the following:
<div *ngIf="user$ | async as user" class="container">
<p>user.name</p>
</div>
Is there a way I can execute code when the div
above finally appears on screen?
A solution without the creation of a new directive is to take advange of
@ViewChild
and@ViewChildren
behaviour:1. ViewChild approach
The important part is If the view DOM changes wich means that in this case this'll only be triggered when the element is created or destroyed.
First declare a variable name for the element, for the sample i used
#userContent
Then add a
@ViewChild
reference inside your component:This solution was provided inside another question, also
@ViewChild
behaviour detail is available here.2. ViewChildren approach
Another solution without using a new directive is to subscribe to
@ViewChildren
change observable, instead of using@ViewChild
put it like this:And then subscribe to it change observable:
I've preferred the last way because to me it was easier to handle observables than validations inside
setter's
, also this approach is closer to the "Event" concept.The ngIf will remove that DOM element and all attached components/directives. So you can just write a simple directive that executes an event when it's first created. When the ngIf transitions from false to true the directive will be created (again, and again, etc...)
Sample HTML: