如何使用 ngIf 检查另一个元素是否存在?

如果存在另一个元素(稍后将动态填充),如何调整一个元素以显示/隐藏?


例如:


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>

我没有其他变量可以监听以使其工作。唯一的线索是让第二个 div 在 #tableData 存在时显示出来。


BIG阳
浏览 124回答 3
3回答

慕村225694

通过注入 DocumenttableData 是否存在> 将令牌放入构造函数中。接下来,使用普通的旧 JavaScript 通过 id 查找元素。视图加载后,检查它是否存在,如下所示: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');}将 generateTableDataAfterDOMIsReady('#container'); 的调用移至 ngOnInit 而不是 ngAfterViewInit 中。@ViewChild 会更好,但仅当标记的 id 指定为 #id 时才有效。

holdtom

最简单的方法是设置一个标志&nbsp; ngAfterViewInit() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Run a library that will populate the table, for example&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//This will create an element with an id tableData&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;generateTableDataAfterDOMIsReady('#container');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.pseudoIsTableDataExists=true&nbsp; &nbsp; }和<div *ngIf="pseudoIsTableDataExists">Data has been generated</div>

慕慕森

简单地说,您可以绑定hidden 属性。超文本标记语言<div [hidden]="!isTableDataExists">&nbsp; &nbsp; Data has been generated</div>成分&nbsp;ngAfterViewInit() {&nbsp; &nbsp; &nbsp;//Run a library that will populate the table, for example&nbsp; &nbsp; &nbsp;//This will create an element with an id tableData&nbsp; &nbsp; &nbsp;generateTableDataAfterDOMIsReady('#container');&nbsp; &nbsp; &nbsp;this.isTableDataExists = true;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5