Angular 2 equivalent of ng-bind-html, $sce.trustAsHTML(), and $compile?

前端 未结 6 926
暖寄归人
暖寄归人 2020-11-30 09:46

In Angular 1.x, we could insert HTML in real-time by using the HTML tag ng-bind-html, combined with the JavaScript call $sce.trustAsHTML(). This go

6条回答
  •  半阙折子戏
    2020-11-30 10:39

    After reading a lot, and being close of opening a new topic I decided to answer here just to try to help to others. As I've seen there are several changes with the latest version of Angular 2. (Currently Beta9)

    I'll try to share my code in order to avoid the same frustration I had...

    First, in our index.html

    As usual, we should have something like this:

    
     ****
      
        Loading...
      
    
    

    AppComponent (using innerHTML)

    With this property you will be able to render the basic HTML, but you won't be able to do something similar to Angular 1.x as $compile through a scope:

    import {Component} from 'angular2/core';
    
    @Component({
        selector: 'my-app',
        template: `
                    

    Hello my Interpolated: {{title}}!

    `, }) export class AppComponent { public title = 'Angular 2 app'; public htmlExample = '
    ' + '' + 'Hello my Interpolated: {{title}}' + '
    ' }

    This will render the following:

    Hello my Interpolated: Angular 2 app!

    Hello my Property bound: Angular 2 app!

    Hello my Interpolated: {{title}}

    AppComponent Using DynamicComponentLoader

    There is a little bug with the docs, documented in here. So if we have in mind that, my code should look now like this:

    import {DynamicComponentLoader, Injector, Component, ElementRef, OnInit} from "angular2/core";
    
    @Component({
        selector: 'child-component',
        template: `
            

    Hello my Interpolated: {{title}}

    ` }) class ChildComponent { title = 'ChildComponent title'; } @Component({ selector: 'my-app', template: `

    Hello my Interpolated: {{title}}!

    End of parent: {{endTitle}}

    `, }) export class AppComponent implements OnInit{ public title = 'Angular 2 app'; public endTitle= 'Bye bye!'; constructor(private dynamicComponentLoader:DynamicComponentLoader, private elementRef: ElementRef) { // dynamicComponentLoader.loadIntoLocation(ChildComponent, elementRef, 'child'); } ngOnInit():any { this.dynamicComponentLoader.loadIntoLocation(ChildComponent, this.elementRef, 'child'); } }

    This will render the following:

    Hello my Interpolated: Angular 2 app!

    Hello my Property bound: Angular 2 app!

    Hello my Property bound: ChildComponent title

    Hello my Interpolated: ChildComponent title

    End of parent: Bye bye!

提交回复
热议问题