Event to fire when an angular *ngIf statement evaluates in template

后端 未结 2 1252
春和景丽
春和景丽 2020-12-18 22:32

If I have the following:

{{user.name}}&l

相关标签:
2条回答
  • 2020-12-18 23:14

    A solution without the creation of a new directive is to take advange of @ViewChild and @ViewChildren behaviour:

    Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

    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

    <div #userContent *ngIf="user$ | async as user" class="container">
      <p>user.name</p>
    </div>
    

    Then add a @ViewChild reference inside your component:

    @ViewChild('userContent') set userContent(element) {
      if (element) {
         // here you get access only when element is rendered (or destroyed)
      }
    }
    

    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:

    @ViewChildren('userContent')
    private userContent: QueryList<any>;
    

    And then subscribe to it change observable:

    userContent.changes.subscribe((d: QueryList<any>) => {
      if (d.length) {
        // here you get access only when element is rendered
      }
    });
    

    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.

    0 讨论(0)
  • 2020-12-18 23:17

    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...)

    @Directive({selector: '[after-if]'})
    export class AfterIfDirective implements AfterContentInit {
        @Output('after-if')
        public after: EventEmitter<void> = new EventEmitter<void>();
    
        public ngAfterContentInit(): void {
           // timeout helps prevent unexpected change errors
           setTimeout(()=> this.after.next());
        }
    }
    

    Sample HTML:

    <div *ngIf="user$ | async as user" (after-if)="your expression">
       <p>{{user.name}}</p>
    </div>
    
    0 讨论(0)
提交回复
热议问题