簡體   English   中英

ng-container的內部HTML,Angular 4?

[英]Inner HTML of ng-container, Angular 4?

我想動態地在我的html代碼中放置一個HTML代碼,所以我寫下面的代碼:

<ng-container [innerHTML]="buttonIcon"></ng-container>

Angular說innerHTML不是ng-container有效屬性
我不想使用如下的第三個html標簽:

<div [innerHTML]="buttonIcon"></div>

那么如何在沒有任何標簽內部html綁定的情況下插入html代碼呢?

你可以使用ngTemplate:

<ng-template #buttonIcon>
    <div> Your html</div>
</ng-template>
<ng-container 
   *ngTemplateOutlet="buttonIcon">
</ng-container>

**請閱讀評論。 這個答案可能是錯的。 我不知道,還沒有再看一遍**

ng-container不會被渲染為html,它只是一個結構指令

Angular是一個分組元素,不會干擾樣式或布局,因為Angular 不會將它放在DOM中

因此沒有將html放入的元素。 你需要使用sub-div。 如果你認為不需要sub-div,那么你很可能也只是用div本身替換ng-container而根本不使用容器。

如果您有任何理由需要更換的DOM元素,你可以使用一個div一個id,然后使用@ViewChild裝飾和ElementRef擺脫控制器訪問nativeElement和設置的outerHTML屬性。

app.component.tml

<div #iconButton></div>

app.component.ts

import { Component, ViewChild, ElementRef, ViewEncapsulation, AfterViewInit }from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent  implements AfterViewInit{
   @ViewChild('iconButton')
    iconButton: ElementRef;

    ngAfterViewInit(){
      this.iconButton.nativeElement.outerHTML = '<button>My button</button>'
    }
}

我們需要使用none作為封裝策略,因為我們的模板只包含要替換的div。

Stackblitz示例: https ://stackblitz.com/edit/angular-fa1zwp

[outerHTML]

將完成替換外部元素的技巧。

在你的情況下

<div [outerHTML]="buttonIcon"></div>

確實,擁有一個干凈的HTML結構非常重要,例如盡可能簡化CSS規則。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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