首页 > 解决方案 > 如何在Angular ngIf中检查SafeHtml类型是否为null

问题描述

如果 SafeHtml(query) 类型为空,我需要隐藏一个 div 元素。现在的问题是,如果我使用 *ngIf="query!=null" 它将不起作用。

从 '@angular/platform-b​​rowser' 导入 { DomSanitizer, SafeHtml };

标签: angulartypescript

解决方案


要检查NullEmpty String,您无需明确检查。只需检查变量内部*ngIf条件。

请检查这个简短的例子:这里

TS

query: SafeHtml;
htmlString = 
`<div style='background:gold'> 
    I am coming from controler with dynamic text --  <b> ${this.checkText} </b>
 </div>`;

constructor(domSantizer: DomSanitizer) {
   this.query = this.htmlString 
   ? domSantizer.bypassSecurityTrustHtml(this.htmlString) 
   :  ''; 
}

HTML

<div *ngIf="query">
    <b> Check with SafeHtml </b>
    <span [innerHTML]="query"> </span>
</div>

推荐阅读