繁体   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