Outputting array of components in Angular 2

后端 未结 2 838
广开言路
广开言路 2021-01-12 10:33

I am building a modal component in Angular 2 (and TypeScript) that will have different views/pages. It won\'t have tabs, but the concept is pretty similar. Basically I am st

相关标签:
2条回答
  • 2021-01-12 11:10

    Angular2 Dynamically Render Template

    import { Component, View, DynamicComponentLoader, ElementRef} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'
    
    @Component({
        selector: 'some-component',
        properties: ['greeting'],
        template: `
        <b>{{ greeting }}</b>
      `
    })
    class SomeComponent { }
    
    
    
    
    @Component({
        selector: 'app'
    })
    @View({
        template: `
        <h1>Before container</h1>
        <div #container></div>
        <h2>After container</h2>
      `
    })
    class App {
        loader: DynamicComponentLoader;
        elementRef: ElementRef;
    
        constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {
        this.laoder = loader;
        this.elementRef = elementRef;
    
        // Some async action (maybe ajax response with html in it)
        setTimeout(() => this.renderTemplate(`
          <div>
        <h2>Hello</h2>
        <some-component greeting="Oh, hey"></some-component>
          </div>
    

    full code : https://github.com/guyoung/GyPractice-Angular2Advanced/tree/master/apps/dynamically_render_template

    0 讨论(0)
  • 2021-01-12 11:11

    You can create a "component factory" as a directive that loads appropriate components using DynamicComponentLoader, based on parameters you pass from your modal.

    <component-factory *ngFor="#view of views" 
        (loaded)="addComponent($event)"
        [name]="view.name" 
        [visible]="view.visible"></component-factory>
    
    @Directive({ selector: 'component-factory' })
    class ComponentFactory {
      @Input() name;
      @Input() visible;
      @Output() loaded = new EventEmitter();
      constructor(
        private _dcl: DynamicComponentLoader, 
        private _eref: ElementRef) {
    
      // import OneCmp, TwoCmp in this file...
      private components: { one: OneCmp, two: TwoCmp }
    
      ngOnInit() {
        this._dcl.loadNextToLocation(
          this.components[this.name], 
          this._eref)
          // pass values to the loaded components
          // and send it's instance to the parent
          .then((ref: ComponentRef) => {
            ref.instance.visible = this.visible;
            this.loaded.emit(ref.instance)
          });
      }
    }
    
    0 讨论(0)
提交回复
热议问题