根据角度2中的DOM状态实例化包含的组件 [英] Instantiate transcluded components depending on their DOM state in angular 2

查看:82
本文介绍了根据角度2中的DOM状态实例化包含的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常用菜单使用案例

<menu>
    <menu-item1></menu-item1>
    <menu-item2></menu-item2>
    <menu-item3></menu-item3>
</menu>

菜单模板

<div *ngIf="open$ | async">
    <ng-content></ng-content>
</div>

我很惊讶地听到所有menu-item*组件(及其所有子代)都将被实例化,尽管它们以DOM和menu组件*ngIf状态存在.即使菜单从未打开过,它们的OnInitAfterViewInit钩子也将被调用,并且即使从DOM中进行了真正的添加删除,也不会触发OnDestroy.这是关于此 https://github.com/angular/angular/issues/13921 <的已解决问题/a>(带有示例的plnkr)和角度文档的问题 https://github.com/angular/angular.io/issues/3099 .

I was suprised to hear that all menu-item* components (and all their children) will be instantiated despite their presence in DOM and menu component *ngIf state. Their OnInit and AfterViewInit hooks will be called even if menu has never been opened and OnDestroy will never fires despite real adding-removing from DOM. Here is a closed issue about this https://github.com/angular/angular/issues/13921 (there is a plnkr with example) and an issue to angular documentation https://github.com/angular/angular.io/issues/3099.

但是这个问题仍然存在-我该如何做才能使菜单项仅在打开菜单时被实例化,并在关闭菜单时被正确销毁?所有挂钩都应仅触发与真实DOM状态相关的

But this issue is still here - how could i do so that menu items will be instantiated only when menu is opened and properly destroyed if closed? All hooks should fire only related to real DOM state.

推荐答案

更新Angular 5

ngOutletContext重命名为ngTemplateOutletContext

另请参见 https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

原始

您可以使用

<menu>
  <template>
    <menu-item1></menu-item1>
    <menu-item2></menu-item2>
    <menu-item3></menu-item3>
  <template>
</menu>

@Component({
  selector: 'menu',
  template: `
<div *ngIf="open$ | async">
  <template [ngTemplateOutlet]="templateRef"></template>
</div>
`
})
class MenuComponent {
  @ContentChild(TemplateRef) templateRef:TemplateRef;
}

您还可以将上下文传递给ngTemplateOutlet(有一些答案显示了如何执行此操作,我没有时间只是不去查找它们)

You can also pass context to ngTemplateOutlet (there are some answers that show how to do that, I don't have time just not to look them up)

这篇关于根据角度2中的DOM状态实例化包含的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆