html - 如何以角度创建 HTML?
问题描述
我已经在 React 上工作了一年。现在,我正在写角度。如何在 ts.file 中创建一段 html 代码?
作为反应,我这样做:
const example = (item: string): React.ReactNode => {
return <p> something.... {item} </p>
}
我想在 Angular8+ 中做同样的事情
我知道一些方法来做到这一点。例如:
const example2= (name: string): string => {
return `
<div>
<p>heyyy ${name}</p>
</div>
`;
};
还有其他方法吗?
解决方案
在 Angular 中,有几种方法可以做到这一点。如果您需要在 typescript 中生成 HTML,然后将其插入到模板中,您可以将 theDomSanitizer
和innerHTML
属性组合使用到其他元素中(例如 a span
)。
下面是我上面建议的一个例子:
hello-world.component.ts
:
@Component({
selector: "hello-world",
templateUrl: "./hello-world.component.html",
styleUrls: ["./hello-world.component.scss"]
})
export class HelloWorld {
innerHTML: string = `<p>Hello, world!</p>`;
}
sanitze.pipe.ts
:
@Pipe({
name='sanitize'
})
export class SanitizePipe {
constructor(private sanitizer: DomSanitizer) { }
transform(value: string): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}
hello-world.component.html
:
<div [innerHTML]="innerHTML | sanitize"</div>
推荐阅读
- javascript - UnhandledPromiseRejectionWarning: TypeError: parsedWeather.sys.sunrise.toLocaleDateString 不是函数
- regex - PowerShell - 查找和修改字符串中的多个文本
- python - 传递给 Dataset.map() 的函数的返回值不受支持
- c++ - 指针初始化覆盖值
- c++ - 关闭流后立即使用外部程序访问文件。(C++)
- ruby-on-rails - Ruby self.extended 被称为实例方法
- ansible - Ansible 条件,带循环的标准输出
- android - 我是否必须使用 LiveData 从 Android 中的房间数据库中读取查询 - Kotlin
- xquery - 具有本地名称“c”的元素范围索引给出 XDMP-ELEMRIDXNOTFOUND
- python - pip 无法安装 imread - gcc-9:错误:无法识别的命令行选项 '-stdlib=libc++'