我正在使用ngComponentOutlet
和Compiler
创建动态组件。但是我遇到了一个问题,我无法绑定动态组件的变量。
代码:
@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。
任何帮助