【问题标题】:html content not showing when using template in angular 6在角度 6 中使用模板时未显示 html 内容
【发布时间】:2018-11-26 11:20:17
【问题描述】:

我正在根据以下示例开发动态模板创建。 example 但我无法获得 html 输出。即)动态内容。 ts 文件:

@Component({
  selector: 'product-item',
  template: `
    <div class="product">
      <ng-container *compile="template; context: this"></ng-container>
    </div>`,
})
export class DynamicItemComponent {
        
  @Input() content: string = `<a (click)='changeEditor('TEXT')'>Click me</a>`;  
  @Input() template: string = `{{content}}`;
    
}

HTML:

<product-item [content]="selectedTemplate.content"></product-item>

如何获得 html 输出。我已经使用了 safethtml 管道,这也不起作用。 提前致谢。

【问题讨论】:

    标签: angular angular-template


    【解决方案1】:

    您可以使用 ng-template 指令创建 HTML 模板。

    <ng-template #anchorRef>
       <a (click)="changeEditor('TEXT')">Click me</a>
    </ng-template>
    

    您可以使用 @Input 装饰器将此 templateRef 作为输入传递给子组件。

    子组件:

    使用 *ngTemplateOutlet 结构指令,

    @Component({
      selector: 'hello',
      template: `
      <h1>Hello !</h1>
      <ng-container *ngTemplateOutlet="name"></ng-container>
      `,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class HelloComponent  {
      @Input() name: TemplateRef<any>;
    }
    

    【讨论】:

    • 谢谢。但是 html 内容是动态的,所以不能使用 ng-template。我的问题是。当我在模板中绑定 html 内容时它正在工作,但上面的示例不起作用。
    • 对于动态 HTML 内容,可以使用 [innerHTML] 属性绑定。 stackoverflow.com/questions/49013217/…
    • 如果我使用 innerhtml,我无法获得愤怒标签事件。 stackoverflow.com/questions/53447577/…
    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    相关资源
    最近更新 更多