angular:绑定动态组件的输入

时间:2018-06-01 12:46:28

标签: angular typescript

我正在使用ngComponentOutletCompiler创建动态组件。但是我遇到了一个问题,我无法绑定动态组件的变量。

代码:

@Component({
    selector: 'app-common-dttable',
    template: `<ng-container *ngComponentOutlet="dynamicComponent;
    ngModuleFactory: dynamicModule;"></ng-container>`,
    styleUrls: ['dttable.component.css']
})

export class DttableComponent implements OnInit {
    @Input() rows: any;  // data of grid
    @Input() cfg: string; // template of dynamic component

    dynamicComponent;
    dynamicModule: NgModuleFactory<any>;

    constructor(private compiler: Compiler) { }

    ngOnInit() {
        this.dynamicComponent = this.createNewComponent(this.rows, this.cfg);
        this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
    }

    createComponentModule(componentType: any) {
        @NgModule({
            imports: [DatatableModule, CommonModule],
            declarations: [
                componentType
            ],
            exports: [componentType],
            entryComponents: [componentType]
        })
        class RuntimeComponentModule {
        }
        return RuntimeComponentModule;
    }

    createNewComponent(rows: any, cfg: string) {
        let template = cfg;

        @Component({
            selector: 'dynamic-component',
            template: template
        })
        class DynamicComponent implements OnInit, AfterViewChecked {

            @ViewChild('tableWrapper') tableWrapper;
            @ViewChild(DatatableComponent) table: DatatableComponent;
            private currentComponentWidth;

            dtrows: any;
            dtcols: any[];

            constructor() { }

            ngOnInit() {
                setTimeout(() => {
                    this.dtrows = rows;
                })
            }

            ngAfterViewChecked(): void {
                if (this.table && this.table.resize && (this.tableWrapper.nativeElement.clientWidth !== this.currentComponentWidth)) {
                    this.currentComponentWidth = this.tableWrapper.nativeElement.clientWidth;
                    setTimeout(() => {
                        this.table.resize();
                    }, 250);
                }
            }

            refresh(newRows: any): void {
                this.dtrows = newRows;
            }

        }
        return DynamicComponent;
    }

}

目前,它可以第一次显示数据。我想将dtrows的{​​{1}}绑定到DynamicComponent的{​​{1}},以便我可以更新数据表。在这种情况下,我不想重新生成新组件。

我正在使用Angular5。

任何帮助

0 个答案:

没有答案