所以我正在使用这个应用程序,其中我使用了ViewContainerRef
和dynamicComponentLoader
,如下所示:
generic.component.ts
export class GenericComponent implements OnInit, OnChanges{
@ViewChild('target', { read: ViewContainerRef }) target;
@Input('input-model') inputModel: any = {};
constructor(private dcl: DynamicComponentLoader) { }
ngAfterViewInit() {
this.dcl.loadNextToLocation(DemoComponent,this.target)
.then(ref => {
if (this.inputModel[this.objAttr] === undefined) {
ref.instance.inputModel = this.inputModel;
} else {
ref.instance.inputModel[this.objAttr] = this.inputModel[this.objAttr];
}
});
console.log('Generic Component :===== DemoComponent===== Loaded");
}
ngOnChanges(changes) {
console.log('ngOnChanges - propertyName = ' + JSON.stringify(changes['inputModel'].currentValue));
this.inputModel=changes['inputModel'].currentValue;
}
}
generic.html
<div #target></div>
因此,它将正确呈现
DemoComponent
中的target
元素。但是当我更改
inputModel
时,我想重置目标元素的视图。我试过
onOnChanges
重置inputModel,它正确地更改了,但是视图没有针对相应的更改进行更新。所以我想知道在更新
ngOnChanges
之后是否可以在inputModel
中重置视图?有输入吗?
最佳答案
this.inputModel
和ref.instance.inputModel
之间没有连接。如果更改,则需要再次复制。
例如:
export class GenericComponent implements OnInit, OnChanges{
componentRef:ComponentRef;
@ViewChild('target', { read: ViewContainerRef }) target;
@Input('input-model') inputModel: any = {};
constructor(private dcl: DynamicComponentLoader) { }
ngAfterViewInit() {
this.dcl.loadNextToLocation(DemoComponent,this.target)
.then(ref => {
this.componentRef = ref;
this.updateModel();
});
console.log('Generic Component :===== DemoComponent===== Loaded");
}
updateModel() {
if(!this.componentRef) return;
if (this.inputModel[this.objAttr] === undefined) {
this.componentRef.instance.inputModel = this.inputModel;
} else {
this.componentRef.instance.inputModel[this.objAttr] = this.inputModel[this.objAttr];
}
}
ngOnChanges(changes) {
console.log('ngOnChanges - propertyName = ' + JSON.stringify(changes['inputModel'].currentValue));
this.inputModel=changes['inputModel'].currentValue;
this.updateModel();
}
}