【发布时间】:2016-07-29 06:36:24
【问题描述】:
我正在动态加载一个组件,它工作正常,除了我可以让它被销毁。
我正在动态加载的组件
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();
}
}
在这个组件的 html 中,我只有一个按钮来删除它,类似的东西
<button (click)="removeComponent()">Remove Component</button>
但是,当 removeComponent() 触发时会引发错误
TypeError: Cannot read property 'destroy' of undefined
我错过了什么?
更新
关于这个问题的更多解释:
[1] 我有 user.component 和 user-list.component。
[2] user.component中有一个按钮调用user-list.component
[3] 单击此按钮时,user-list.component 应加载到特定区域,这是有效的。
[4] user-list.component中有一个按钮可以关闭这个动态加载的组件。
[5] 当这个按钮被点击时,user-list.component 应该被销毁。
用户组件
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;
});
}
}
但是,我听说以这种方式动态加载组件已被弃用。我们应该使用 ComponentResolver 和 ViewContainerRef。对吗?
【问题讨论】:
-
您没有为
_componentRef分配任何值,这就是它未定义的原因。顺便说一句,“动态加载”是什么意思? -
请用完整代码更新您的问题。
-
看看medium.com/tixdo-labs/…,它展示了如何获得
ComponentRef -
大家好,我刚刚更新了我的问题。如果还不清楚,请告诉我
-
DCL 已弃用。请改用
ViewContainerRef.createComponent()。有关示例,请参见 stackoverflow.com/questions/36325212/…。
标签: typescript angular angular2-components