When I create a component using ViewContainerRef
and assign instance to a property of parent component, which is responsible for child component creation, do I need to set this property to null
after I call ViewContainerRef.clear()
if I want memory to be freed?
No, if you assign parent component property to componentRef
angular won't remove component from memory.
Angular only destroys component and removes its own references to this component. But reference to componentRef remains to live in your component property. So i would assign null
to it. This way garbage collect will be able to clear memory
Plunker Example (add => clear => check)
@Component({
selector: 'my-app',
template: `
<div>
<button (click)="addComponent()">Add component</button>
<div #container></div>
<button (click)="clear()">Clear</button>
<button (click)="check()">check</button>
</div>
`,
})
export class App {
comp: ComponentRef<DynamicComponent>;
constructor(
private vcRef: ViewContainerRef,
private resolver: ComponentFactoryResolver) {}
addComponent() {
let factory = this.resolver.resolveComponentFactory(DynamicComponent);
this.comp = this.vcRef.createComponent(factory);
}
clear() {
this.vcRef.clear();
}
check() {
alert(this.comp);
}
}
See also
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With