동적으로 구성 요소를로드하고 있으며이를 파손시킬 수있는 것과는 별개로 작동합니다. 동적 Angular2 ComponentRef TypeError : 정의되지 않은 'destroy'속성을 읽을 수 없습니다.
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에서
를로드되고내 구성 요소가 나는 경우 removeComponent() 화재를 제거하는 단지 버튼, 그러나
<button (click)="removeComponent()">Remove Component</button>
같은 것을 가지고 오류가 발생했습니다
TypeError: Cannot read property 'destroy' of undefined
내가 무엇을 놓치고 있습니까? 문제에 대한
UPDATE
더 설명 : [1] 내가 user.component 및 사용자 list.component 있습니다. [2] user.component에 user-list.component를 호출하는 버튼이 있습니다. [3]이 버튼을 클릭하면 user-list.component가 작동중인 특정 영역에로드됩니다. [4] user-list.component에 동적으로로드 된이 구성 요소를 닫을 수있는 버튼이 있습니다. [5]이 버튼을 클릭하면 user-list.component를 삭제해야합니다.
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;
});
}
}
그러나, 동적으로 그 방법이 사용되지 않습니다로드하는 구성 요소를 들었습니다. ComponentResolver와 ViewContainerRef를 사용해야합니다. 그게 맞습니까?
. Btw, "동적로드"란 무엇입니까? – martin
질문을 전체 코드로 업데이트하십시오. – micronyks
https://medium.com/tixdo-labs/angular-2-dynamic-component-loader-752c3235bf9#.tu6gcgw69에서 'ComponentRef'를 얻는 방법을 보여줍니다. –