要防止HTML标签被转义,可以使用Angular的内置管道(pipe)来实现。以下是一个示例代码,演示了如何将字符串变量传递给子组件时防止HTML标签被转义:
父组件中的模板:
父组件中的代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
htmlData = 'Hello Angular
';
}
子组件中的模板:
子组件中的代码:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() htmlContent: string;
}
在这个示例中,父组件通过属性绑定将HTML内容字符串传递给子组件。在子组件的模板中,使用了[innerHTML]
属性绑定来将htmlContent
渲染为HTML内容,而不是将其作为纯文本显示。这样就可以防止HTML标签被转义。