C
C
Coder3212016-10-21 21:19:19
JavaScript
Coder321, 2016-10-21 21:19:19

Angular 2 how to set template dynamically?

I have a component, I want to set completely different templates for it depending on the parameters passed to it, how can I do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-10-21
@yurzui

See this answer How to initialize router in Angular2?
It's a bit outdated code
1) Using the compiler
Create a directive that will dynamically load a component with the desired template

@Directive({ selector: 'html-outlet' })
export class HtmlOutlet {
  @Input() html: string;
  cmpRef: ComponentRef<any>;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }

  ngOnChanges() {
    const html = this.html;
    if (!html) return;
    
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
    
    @Component({
      selector: 'dynamic-comp',
      template: html
    })
    class DynamicHtmlComponent  {};

     @NgModule({
      imports: [CommonModule],
      declarations: [DynamicHtmlComponent]
    })
    class DynamicHtmlModule {}

    this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
      .then(factory => {
        const moduleRef = factory.ngModuleFactory.create(this.vcRef.parentInjector);
        
        const compFactory = factory.componentFactories.find(x => x.componentType === DynamicHtmlComponent);
        const cmpRef = this.vcRef.createComponent(compFactory, 0, moduleRef.injector);
      });
  }
  
  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Then we use it this way:
Instead of templatemaybe templateUrlParameters @Input@Outputcan be screwed up later if necessary
An example of how it works
2) If you have a strictly defined set of components, then you can consider another option:
In this case, these components need to be added:
  1. to entryComponentsan array of your module or component
  2. or through a ANALYZE_FOR_ENTRY_COMPONENTSprovider

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question