I am loading a component dynamically and it is working fine apart from I can make it to be destroyed.
My component that is being loaded dynamically
import { Component, ElementRef, ComponentRef } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'app-user-list',
templateUrl: 'user-list.component.html',
})
export class UserListComponent {
_componentRef: ComponentRef<any>;
constructor(private _elementRef: ElementRef) {}
removeComponent()
{
this._componentRef.destroy();
}
}
And in html of this component I have just a button to remove it, something like it
<button (click)="removeComponent()">Remove Component</button>
However, when removeComponent() fires an error is thrown
TypeError: Cannot read property 'destroy' of undefined
What I am missing?
UPDATE
More explanation about the issue:
[1] I have user.component and user-list.component.
[2] There is a button in the user.component to call user-list.component
[3] When this button is clicked, user-list.component should load in a specific area, which is working.
[4] There is a button in the user-list.component to close this component that was loaded dynamically.
[5] When this buttons is clicked, user-list.component should be destroyed.
UserComponent
import { Component, DynamicComponentLoader, Injector, ApplicationRef } from '@angular/core';
import { UserListComponent } from "../user-list/user-list.component";
@Component({
moduleId: module.id,
selector: 'app-users',
templateUrl: 'users.component.html',
styleUrls: ['users.component.css'],
directives: [TestComponent, CreateUserForm]
})
export class UsersComponent implements OnInit, AfterViewInit {
public constructor(
private _dcl: DynamicComponentLoader,
private _injector: Injector,
private _appRef: ApplicationRef
){}
loadUserList()
{
this._dcl.loadAsRoot(UserListComponent, '#user-list', this._injector)
.then((compRef: ComponentRef<UserListComponent>) => {
(<any>this._appRef)._loadComponent(compRef);
return compRef;
});
}
}
However, I've heard that load component dynamically that way is deprecated. We should use ComponentResolver and ViewContainerRef. Is that right?