更改检测后如何在angular2中重置ViewContainerRef?

时间:2016-07-18 12:36:54

标签: javascript typescript angular angular2-template

所以我正在开发这个应用程序,我在其中使用了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内的视图?

任何输入?

1 个答案:

答案 0 :(得分:1)

this.inputModelref.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();
   }
}