timthekoder
timthekoder

Reputation: 435

How to use ngIf to check if another element exists?

How do I condition an element to show/hide if another element (which will be dynamically populated at a later time) exists?

For example:

app.component.ts

export class AppComponent implements OnInit, AfterViewInit {

    ngOnInit(): void {}

    ngAfterViewInit() {

         //Run a library that will populate the table, for example
         //This will create an element with an id tableData
         generateTableDataAfterDOMIsReady('#container');

    }

}

app.component.html

<div id="container">
    <!-- When the javascript function is invoked, it will dynamically change the content inside this div and generate a <div id="tableData"></div>
</div>
<div *ngIf="pseudoIsTableDataExists()">Data has been generated</div>

There is no other variable I can listen to in order to make it work. The sole clue is to condition the second div to show itself when #tableData exists.

Upvotes: 1

Views: 3939

Answers (3)

Nicholas K
Nicholas K

Reputation: 15423

Check for the existence of tableData by injecting the Document token into the constructor. Next, use plain old JavaScript to find the element by id. Once the view loads, check if it is present as shown below:

import { Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";

constructor(@Inject(DOCUMENT) document) {
}

ngAfterViewInit() {
   if (document.getElementById('tableData')) {
      // success scenario
   } else {
      // failure
   }
}

ngOnInit() {
   generateTableDataAfterDOMIsReady('#container');
}

Move the call of generateTableDataAfterDOMIsReady('#container'); to the ngOnInit rather than in the ngAfterViewInit.

@ViewChild would be better but it works only if the id of the tag is specified as #id.

Upvotes: 1

skdonthi
skdonthi

Reputation: 1442

Simply, you can bind hidden property.

HTML

<div [hidden]="!isTableDataExists">
    Data has been generated
</div>

Component

 ngAfterViewInit() {

     //Run a library that will populate the table, for example
     //This will create an element with an id tableData
     generateTableDataAfterDOMIsReady('#container');
     this.isTableDataExists = true;
}

Upvotes: 0

Antoniossss
Antoniossss

Reputation: 32507

Easiest way is to set a flag

  ngAfterViewInit() {

         //Run a library that will populate the table, for example
         //This will create an element with an id tableData
         generateTableDataAfterDOMIsReady('#container');
         this.pseudoIsTableDataExists=true
    }

and

<div *ngIf="pseudoIsTableDataExists">Data has been generated</div>

Upvotes: 0

Related Questions