[英]Angular [innerHtml]: how to render additional elements inside an element with [innerHtml] directive
具有[innerHtml]指令的元素似乎只是在该元素内添加了声明的html字符串,仅此而已;
通过这次的堆栈闪电 ,我试图在这样的元素内添加一些东西,但是没有用;
<div [innerHTML]="safeHtml(item.isi)"><p>new word - will not show</p></div>
有没有一种方法可以使用[innerHtml]指令在元素内添加更多HTML? 换句话说,如何使示例中的堆叠闪电战正常工作?
您为何使用[innerHTML],因为您的item.isi不是html元素; 我们使用innerHTML呈现html结果; 就像您的item.isi是<p>My name</p>
; 如果它不是html元素而无需使用innerHTML,则可以在div内简单地使用{{item.isi}},因此您也可以呈现其他html元素
您可以尝试使用ElementRef
,如果您想追加元素而不是替换完整的html,
html
<div #Container>
add here
</div>
ts文件
export class AppComponent implements AfterViewInit {
@ViewChild('Container') container: ElementRef ;
content = [
{judul: "Judul 1", isi:"<div id='title_1'>Isinya</div>"},
{judul: "Judul 2", isi:"<div id='title_2'>pranay</div>"},
];
ngAfterViewInit() {
this.content.forEach( (item,index) =>{
this.container.nativeElement.insertAdjacentHTML('beforeend', `<div id="title${index}">${item.judul}</div>`);
this.container.nativeElement.insertAdjacentHTML('beforeend', `${item.isi}`);
});
}
但是不推荐使用elementref的方式。
以上代码的输出
您可以看到它在添加内容之后, 在此处一一添加
查找: 工作演示
而不是在组件中使用函数(它不能作为试图将html传递给您的脚本文件的html模板),您应该创建如下所示的管道
html.pipe.ts
import { Component, Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'html'
})
export class HtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
并像这样使用
html
<div *ngFor="let item of content">
<h3 [innerHTML]="item.judul | html ">add</h3>
<div [innerHTML]="item.isi | html "><p>new word</p></div>
</div>
查找: 工作演示
据我了解您的问题,使用内部html替换内部html。 因此,旧值将替换为对象中的值。
我了解您要遵循此方法,因为您要显示对象中的值。
因此,更好的方法是使用管道。 也许。 只要检查这个答案。 如果有帮助。 点击这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.