bellotas
bellotas

Reputation: 2461

Calling a method after *ngIf - Angular

I would like to call a method every time that one of my templates appear

<div *ngIf="test" class="col-md-8">
    <select class="form-control">
        <option type="text>{{test}}</option>
    </select>
</div>

is it possible to execute a method whentest contains a value and run the *ngIf?

Upvotes: 0

Views: 2084

Answers (1)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

You're approaching it the wrong way. Do not call methods because something happens in DOM -- that goes against the pattern that Angular is trying to enforce.

Your model (from the .ts file) should control the template, not the other way around. Instead of thinking "call this method when a part of template disappears", go a step back and ask yourself:

What is causing the *ngIf to toggle component?

There's your answer. For example, say you have something like the following.

toggle() {
  this.flag = !this.flag
}

That's the place where your model changes. If you want something else to happen when the flag is switched, do it there.

toggle() {
  doSomething()
  this.flag = !this.flag
}

If you want it to happen only when the flag is raised (becomes true), just use a conditional statement.

toggle() {
  if (!this.flag) {
    doSomething() // only when turning from false to true
  }
  this.flag = !this.flag
}

Upvotes: 2

Related Questions