【问题标题】:Angular2 - Interpolate string with htmlAngular2 - 用 html 插入字符串
【发布时间】:2016-11-11 18:07:50
【问题描述】:

如何使用 angular2 用 html 插入字符串。我知道在 angular 1.x 中有 $interpolate(templateString)(miniScope); 但我没有找到 angular2 相同的。

假设我有一个这样的模板:Hello my name is {{name}}

绑定就像name: "<strong>Pardeep</strong>"

所以我想要这样的结果

你好,我的名字是 Pardeep

Refer for angular1

for angular2 see here but i'm unable to understand clearly

有什么帮助吗?

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    您可以简单地使用[innerHTML] 指令来完成它。

    http://plnkr.co/edit/6x04QSKhqbDwPvdsLSL9?p=preview

    import {Component, Pipe} from '@angular/core'
    
    @Component({
      selector: 'my-app',
      template: `
                Hello my name is <span [innerHTML]="myName"></span> 
      `,
    })
    export class AppComponent {
    
      myName='<strong>Pardeep</strong>';
    
    }
    

    更新:

    我检查了它在 RC.1 发布后不能以这种方式工作。

    假设要使其与RC.4一起使用,您可以使用DomSanitizationService,如下所示,

    @Component({
      selector: 'my-app',
    
      template: `
        <div [innerHTML]="myCheckbox"></div>
      `,
    })
    export class AppComponent {
    
      dangerousUrl='<input type="checkbox">';
    
      constructor(sanitizer: DomSanitizationService) {
    
        this.myCheckbox= sanitizer.bypassSecurityTrustHtml(this.dangerousUrl);
      }
    }
    

    http://plnkr.co/edit/Yexm1Mf8B3FRhNch3EMz?p=preview

    【讨论】:

    • 我知道,如果myName='&lt;input type="checkbox"&gt;'; 怎么办?
    • 现在检查它是否适用于DomSanitizationService API。
    • innerHTML 仍然有效,除非您真的有,否则您不想信任 html...查看“内容安全”下的文档angular.io/docs/ts/latest/guide/…
    猜你喜欢
    • 2015-02-02
    • 1970-01-01
    • 2022-01-02
    • 2013-01-23
    • 1970-01-01
    • 2021-03-13
    • 2015-09-22
    • 2019-01-20
    • 2014-11-11
    相关资源
    最近更新 更多