6

I was looking at issue at: https://stackoverflow.com/a/44737636/973651

I've a div with an ngIf condition, and I'd like to capture an event for when the div gets rendered. Supposedly, you can use the AfterContentInit event. The article I cited above, shows an example, which I've replicated but no luck in getting it to work.

I don't know what I'm doing wrong, but I can't get this to work. I get no errors, but it doesn't work for me.

My directive is defined as:

import { AfterContentInit, EventEmitter, Output, Directive } from '@angular/core';

@Directive({ selector: '[after-if]' })
export class AfterIfDirective implements AfterContentInit {
  @Output('after-if')
  public after: EventEmitter<AfterIfDirective> = new EventEmitter();

  public ngAfterContentInit(): void {
    debugger;
    setTimeout(() => {
      // timeout helps prevent unexpected change errors
      this.after.next(this);
    });
  }
}

In my page component I import.

import { AfterIfDirective } from '../directives/after-if';


@NgModule({
  providers: [],
  imports: [NgModel, BrowserAnimationsModule, HttpClientModule, 
      AfterIfDirective],
  exports: [NgModel, BrowserAnimationsModule, AfterIfDirective]
})

and in the html:

<div *ngIf="chkTearline.checked; else NotTearline" (after-if)="Clicked()">

what am I missing?

Does this not work in Angular 5?

  Clicked() {
    console.log('something got clicked');
  }
luiscla27
  • 4,956
  • 37
  • 49
Les Stockton
  • 81
  • 1
  • 6
  • Can you post your code with the Clicked function? Also drop in a console log in the `setTimeout` to see if it's firing in there. – Mathew Berg May 08 '18 at 20:34
  • here's the Clicked function. Clicked() { console.log('something got clicked'); } – Les Stockton May 08 '18 at 20:53
  • why so strange selector name and input name ? whats wrong with default Angular style afterIf? – Sharikov Vladislav May 08 '18 at 22:12
  • Possible duplicate of [Event to fire when an angular \*ngIf statement evaluates in template](https://stackoverflow.com/questions/44472771/event-to-fire-when-an-angular-ngif-statement-evaluates-in-template) – luiscla27 May 08 '19 at 00:53

1 Answers1

13

You can use setter like in example below:

template:

<div #elementToCheck *ngIf="expr"></div>

component:

@ViewChild('elementToCheck') set elementToCheck () {
  // here you get access only when element is rendered (or destroyed)
}
luiscla27
  • 4,956
  • 37
  • 49
Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87