【问题标题】:How to check SafeHtml type for null in Angular ngIf如何在Angular ngIf中检查SafeHtml类型是否为null
【发布时间】:2021-05-27 11:16:08
【问题描述】:

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

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

【问题讨论】:

  • 你能分享你的当前密码吗?
  • 查询:SafeHtml;
  • 似乎 SafeHtml 是复杂类型,这就是为什么不能等同于空检查。

标签: angular typescript


【解决方案1】:

要检查 NullEmpty String 您无需明确检查。 只需检查 *ngIf 条件中的变量即可。

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

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>

【讨论】:

  • 从“@angular/core”导入{组件,版本};从 '@angular/platform-b​​rowser' 导入 { DomSanitizer, SafeHtml }; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) 导出类 AppComponent { name = "Angular" + VERSION 。重大的; checkNull = null; checkEmpty = ""; checkText = "测试";查询:SafeHtml; }
  • 你可以试试'查询'类型。
  • 我已经更新了例子,你可以通过删除文本去检查它。一旦htmlstring 为空,整个块将从DOM 中删除
  • 这是正确的。它排除了nullundefined 和空。
猜你喜欢
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 2016-12-09
  • 2018-07-25
  • 2019-05-08
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
相关资源
最近更新 更多