簡體   English   中英

Angular [innerHtml]:如何使用[innerHtml]指令在元素內渲染其他元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM