How to place a dynamic component in a container

前端 未结 3 1114
面向向阳花
面向向阳花 2020-12-01 03:26

I want to create dynamic components and insert views of these components to a container.

I think this can be achieved by ViewContainerRef.

But I don\'t know,

3条回答
  •  情深已故
    2020-12-01 04:04

    I did something like that for my app. To load datas in a table.

    To do that I've creat a directive :

    directives: [TableDirective]
    

    And then I use it like that :

    @ViewChild(TableDirective) tableDirective:TableDirective;
    
    ngAfterViewInit() {
        setTimeout(_=>this.load());
    }
    
    load() {
        this.tableDirective.loadTable(*ADirectiveToLoad*);
    }
    

    The TableDirective File :

    import { Component, DynamicComponentLoader, ViewContainerRef } from 'angular2/core';
    
    @Component({
        selector: "my-table",
        template: ``
    })
    
    export class TableDirective {
        constructor(
            private dcl:DynamicComponentLoader,
            private viewContainerRef:ViewContainerRef) {
        }
    
    public loadTable(base:any) {
        this.viewContainerRef.clear();
        this.dcl.loadNextToLocation(base, this.viewContainerRef);
    }
    }
    

    This will load datas in my table, depend of the Directive I send. For exemple :

    import { Component, OnInit } from 'angular2/core';
    
    @Component({
        selector: "my-data",
        templateUrl: "app/_includes/table/actionnaire/table.html"
    })
    
    export class ActionnaireDirective implements OnInit {
        private entity:any;
    
    ngOnInit() {
        this.entity = ACTIONNAIRES_PORTEUR;
    }
    }
    
    var ACTIONNAIRES_PORTEUR:Actionnaire[] = [
        {"id": 1, "nom": "Test", "prenom": "Testeur", "dateNaissance": "15/05/1995"}
    ];
    
    export class Actionnaire {
        id:number;
        nom:string;
        prenom:string;
        dateNaissance:any;
    }
    

    I'm also new with Angular :x

提交回复
热议问题