jemtan990
jemtan990

Reputation: 453

How do I detect that an element within an *ngIf has loaded in order to execute code on it?

I have two divs with components inside. On those divs, I have *ngIfs to toggle between the two. In my component.ts, I'm calling .setAttribute on each of those. The problem I have is that the components are coming back undefined at the time my code is executed.

For example:

<div *ngIf="something"><component-one some-attribute></component-one></div>
<div *ngIf="!something"><component-two some-attribute></component-two></div>
  updateAttribute() {
    this.componentOne = document.getElementsByTagName('component-one')[0];
    this.componentTwo = document.getElementsByTagName('component-two')[0];
    console.log(this.componentOne); // <- this is coming back undefined at this point.
    if (this.componentOne) {
      // so we're not making it into here.
      this.componentOne.setAttribute('some-attribute', this.someAttribute);
    }
    if (this.componentTwo) {
      this.componentTwo.setAttribute('some-attribute', this.someAttribute);
    }
  }

Is there a way to detect that the elements/components have loaded?

Upvotes: 1

Views: 654

Answers (2)

Maihan Nijat
Maihan Nijat

Reputation: 9355

You are directly manipulating the DOM which is not recommended. There is a better Angular way to achieve this. But if you want to go with this:

updateAttribute() {
     if (this.something) {
         this.componentOne = document.getElementsByTagName('component-one')[0];
         this.componentOne.setAttribute('some-attribute', this.someAttribute);
     } else {
         this.componentTwo = document.getElementsByTagName('component-two')[0];
         this.componentTwo.setAttribute('some-attribute', this.someAttribute);
     }
}

Upvotes: 1

mukund patel
mukund patel

Reputation: 1052

Use @output here and emit the function from child component.You can get more about event emission here

Upvotes: 2

Related Questions