Article From:https://segmentfault.com/q/1010000011711395
Question:

It is found that after the dynamic component is created, an instance of the dynamic component (componentRef. instance) is used to change the properties of the dynamic component, such as:
componentRef.instance.xxx=”123″
The bound {{xxx}} on the interface will not be updated.
But the console output shows that the XXX has been changed.
Using functions directly in dynamic component classes can change XXX, and {{xxx}} is updated in real time.
If you can make use of componentRef, do you want to update the binding data in real time?

Answer 0:

The only effective measure is coverage.instance The value will not trigger.OnChanges The hook.

@Component({
    template: `
        I'm testing template {{data}}.`})Export class CustomComponent implements OnInit {@Input () public data:String;Public ngOnInit () {Console.log (this.data);SetTimeout (() => {Console.log (this.data);}, 3000);}}
export class HomeComponent implements OnInit {
    constructor(
        private viewContainerRef: ViewContainerRef,
        private cfr: ComponentFactoryResolver
    ) {}
    public ngOnInit() {
        let factory = this.cfr.resolveComponentFactory(CustomComponent);
        let componentRef = this.viewContainerRef.createComponent(factory);
        componentRef.instance.data = 'hello';
        setTimeout(() => {
            componentRef.instance.data = 'bye';
        }, 2000);
    }
}

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *