Dynamic template in templatURL in angular2

前端 未结 5 1017
醉话见心
醉话见心 2020-11-30 06:52

I have been using ng-include in angular 1 whenever I had to include a tamplate dynamically in the page.

Now how to acheive this in angular 2. I have tried searching

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 07:31

    Following @binariedMe and this blog post http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/, I was able to construct a solution that may work for you. Using an AJAX call and creating the custom component dynamically from the returned html content should fix this problem in creating a new my-ng-include custom directive.

    import {
      Component,
      Directive,
      ComponentFactory,
      ComponentMetadata,
      ComponentResolver,
      Input,
      ReflectiveInjector,
      ViewContainerRef
    } from '@angular/core';
    import { Http } from '@angular/http';
    
    export function createComponentFactory(resolver: ComponentResolver, metadata: ComponentMetadata): Promise> {
        const cmpClass = class DynamicComponent {};
        const decoratedCmp = Component(metadata)(cmpClass);
        return resolver.resolveComponent(decoratedCmp);
    }
    
    @Directive({
        selector: 'my-ng-include'
    })
    export class MyNgInclude {
    
        @Input() src: string;
    
        constructor(private vcRef: ViewContainerRef, private resolver: ComponentResolver, private http: Http) {
        }
    
        ngOnChanges() {
          if (!this.src) return;
    
          this.http.get(this.src).toPromise().then((res) => {
            const metadata = new ComponentMetadata({
                selector: 'dynamic-html',
                template: res.text(),
            });
            createComponentFactory(this.resolver, metadata)
              .then(factory => {
                const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
                this.vcRef.createComponent(factory, 0, injector, []);
              });
          });
        }
    }
    

    Just simply use it as follows:

    
    

提交回复
热议问题