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

前端 未结 6 930
暖寄归人
暖寄归人 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:27

    DynamicComponentLoader is deprecated, you can use ComponentResolver instead

    You could use this directive, add pipes if you need additional data manipulation. It also allows for lazy loading, you don't need it in your case, but it's worth mentioning.

    Directive(I found this code and made some changes, you can do that too to make it fit your taste or use it as is):

    import { Component, Directive, ComponentFactory, ComponentMetadata, ComponentResolver, Input, ReflectiveInjector, ViewContainerRef } from '@angular/core';
    declare var $:any;
    
    export function createComponentFactory(resolver: ComponentResolver, metadata: ComponentMetadata): Promise> {
        const cmpClass = class DynamicComponent {};
        const decoratedCmp = Component(metadata)(cmpClass);
        return resolver.resolveComponent(decoratedCmp);
    }
    
    @Directive({
        selector: 'dynamic-html-outlet',
    })
    export class DynamicHTMLOutlet {
      @Input() htmlPath: string;
      @Input() cssPath: string;
    
      constructor(private vcRef: ViewContainerRef, private resolver: ComponentResolver) {
      }
    
      ngOnChanges() {
        if (!this.htmlPath) return;
        $('dynamic-html') && $('dynamic-html').remove();
        const metadata = new ComponentMetadata({
            selector: 'dynamic-html',
            templateUrl: this.htmlPath +'.html',
            styleUrls:  [this.cssPath]
        });
        createComponentFactory(this.resolver, metadata)
          .then(factory => {
            const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
            this.vcRef.createComponent(factory, 0, injector, []);
          });
      }
    }
    

    Example how to use it:

    import { Component, OnInit } from '@angular/core';
    import { DynamicHTMLOutlet } from './../../directives/dynamic-html-outlet/dynamicHtmlOutlet.directive';
    
    @Component({
      selector: 'lib-home',
      templateUrl: './app/content/home/home.component.html',
      directives: [DynamicHTMLOutlet]
    })
    export class HomeComponent implements OnInit{
        html: string;
        css: string;
    
        constructor() {}
    
        ngOnInit(){
        this.html = './app/content/home/home.someTemplate.html';
        this.css = './app/content/home/home.component.css';
        }
    
      }
    

    home.component.html:

    
    

提交回复
热议问题