Sum*_*wal 18 angular2-components angular
我有一个父组件,它在点击链接时打开一个新组件,这个新组件应该有一个关闭按钮,在关闭时向父发送一个关闭消息并销毁自己.
我们可以使用ngOnDestroy方法发送结束消息,但是如何调用子组件的销毁.
<parent>
<child></child> //child to be opened on click but close
//event should be inside the child componenet
</parent>
Run Code Online (Sandbox Code Playgroud)
如果我在这里遇到一些概念错误,请纠正我.谢谢
Gün*_*uer 29
如果添加使用分量ViewContainerRef.createComponent()等所示角2个动态卡口与用户点击选择部件,然后当你通过该组件可以破坏本身cmpRef到所创建的组件.
否则我不认为有办法.您可以将值传递给父级,以便*ngIf删除组件.
<child *ngIf="showChild" (close)="showChild = false"></child>
Run Code Online (Sandbox Code Playgroud)
class ParentComponent {
showChild:boolean = true;
}
Run Code Online (Sandbox Code Playgroud)
class ChildComponent {
@Output() close = new EventEmitter();
onClose() {
this.close.emit(null);
}
}
Run Code Online (Sandbox Code Playgroud)
Ark*_*osh 13
这是另一种方法。这在组件本身内起作用;无需与外部组件通信。
// imports
export class SelfDestroyableComponent implements OnInit {
// other code
constructor(private host: ElementRef<HTMLElement>) {}
// whatEver function name you want to give
onCloseClicked() {
this.host.nativeElement.remove();
}
// other code
}
Run Code Online (Sandbox Code Playgroud)
Ser*_*iug 12
不确定这种解决方案的清洁度,但我用过:
this.viewContainerRef
.element
.nativeElement
.parentElement
.removeChild(this.viewContainerRef.element.nativeElement);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20027 次 |
| 最近记录: |