因此,我正在开发这个应用程序,其中我使用了 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>
因此它可以正确渲染 target
元素中的 DemoComponent
。
但是当我更改inputModel
时,我想重置目标元素的 View 。
我尝试 onOnChanges
重置 inputModel ,它已正确更改,但 View 未针对相应更改进行更新。
所以我想知道在 inputModel
更新后是否可以重置 ngOnChanges
内的 View ?
有任何输入吗?
最佳答案
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();
}
}
关于javascript - 如何在更改检测后重置 Angular2 中的 ViewContainerRef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436901/