Angular原始HTML绑定|innerHtml例子

1,092 阅读2分钟

本教程解决了Angular应用中html绑定的以下问题

  • 如何在Angular中进行字符串原始html绑定?
  • 用html标签渲染html字符串
  • Angular中的innerHtml属性如何工作?
  • 如何用DomSanitizer对html标签内容进行消毒?
  • innerhtml改变事件处理程序考试

在Angular中,使用双向绑定的语法来绑定属性和事件是很简单的。

属性绑定可以通过以下语法来完成

[property]="javascriptexpression"

事件绑定的语法见下图

(event)="javascriptexpression"

属性和事件绑定即双向绑定的语法是

[(ngModel)]="property"

JavaScript表达式可以是json对象的值和属性,也可以是JavaScript函数。

假设,有时我们想绑定HTML响应,而不是JSON响应。

在Angular应用程序中,HTML绑定是如何工作的

使用innerHtml属性绑定,我们可以将HTML内容以字符串的形式绑定。

innerHtml 属性可以通过以下两种方式添加到html标签中

语法:

<div [innerHTML]="variable"></div>
<div innerHTML="{{variable}}"></div>

这里有一个typescript组件

创建了变量内容,用来保存html标签的字符串

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  content: string;
  constructor() {
    this.content = "html response";
  }
}

这里是html组件

Angular将innerHtml内容视为不安全内容,因此它自动进行消毒。

<h3>
  Angular html binding Innerhtml example
</h3>
<span [innerHtml]="content"></span>

由于原始的html内容被传递给Angular组件,我们必须检查html是否被信任。

那么,如何手动对Angular的原始html进行消毒?

  • 在angular组件中导入DomSanitizer
  • 宣告内容类型的变量SafeHtml
  • 传递内容bypassSecurityTrustHtml,并返回可信的安全的html字符串内容
import { Component } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  content: SafeHtml;
  constructor(private sanitizer: DomSanitizer) {
    this.content = this.sanitizer.bypassSecurityTrustHtml(
      "html response"
    );
  }
}

使用innerHtml改变html内容字符串中的事件处理程序

html标签字符串内容包含事件作为内容的一部分,那么你如何启动一个点击事件绑定处理器。

在Angular中,一旦内容被加载,事件监听器就会被附加到处理程序上。

ngAfterViewChecked 使用的调用方法是一个回调方法,每当检测到变化时就运行。

在下面这个例子中,按钮的定义是用innerHtml来表达的。

一旦按钮被渲染,我们将在ngAfterViewChecked method ElementRefQuerySelector 方法中加入点击事件绑定,以使用id来选择DOM按钮。

下面是一个完整的innerHtml事件监听器的例子

import { Component, ElementRef } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  content: SafeHtml;

  constructor(private elementRef: ElementRef, private sanitizer: DomSanitizer) {
    this.content = this.sanitizer.bypassSecurityTrustHtml(
      '

Stackblitz代码

你可以找到本教程的代码

总结

综上所述,Angular innerHtml属性提供了html字符串内容的动态绑定,同时使用ngAfterViewChecked ,我们可以绑定事件监听器。