html - 当 ngIf 为 false 时构建 Angular4 ng-content

标签 html angular typescript angular2-template

我对新的 ng-content 嵌入有疑问。

假设我有一个组件 my-component,它在其 ngOnInit() 函数中在加载时执行一些繁重的操作(目前,只是一个 console .log()).

我有一个包装器,它通过嵌入显示内容 (my-wrapper.component.html)。

<ng-content></ng-content>

如果我这样设置环境,日志语句不会显示:

<my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>

我假设 my-wrapper 组件没有构建,所以内容被忽略了。

但是如果我尝试将逻辑移动到 my-wrapper 组件中,就像这样 (my-wrapper.component.html):

<ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>

我总是看到 console.log() 输出。我猜,my-component 被构建然后存储起来,直到 *ngIfmy-wrapper 中变为 true >.

目的是构建一个通用的“列表项+详细信息”组件。假设我有一个包含 N 个概览元素 (my-wrapper) 的列表,它们在 *ngFor 循环中呈现。这些元素中的每一个都有自己的详细信息组件 (my-component),一旦我决定显示特定项目的更多信息,它就应该加载自己的数据。

概览.html:

<ng-container *ngFor="let item of items">
    <my-wrapper>
        <my-component id="item.id"></my-component>
    </my-wrapper>
</ng-container>

我的包装器.component.html:

<div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail">
    <ng-content></ng-content>
</div>

有没有办法告诉 Angular 在需要添加到页面之前忽略嵌入的内容?类似于 AngularJS 中的情况。

最佳答案

根据@nsinreal 的评论,我找到了答案。我觉得它有点深奥,所以我试着把它贴在这里:

答案是使用 ng-template*ngTemplateOutlet

my-wrapper 组件中,像这样设置模板 (my-wrapper.component.html):

<div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail" [hidden]="!isInitialized">
    <ng-container *ngTemplateOutlet="detailRef"></ng-container>
</div>

请注意,那里的 [hidden] 并不是真正必要的,它会隐藏子项的“原始”模板,直到它决定完成加载。请确保不要将它放在 *ngIf 中,否则 *ngTemplateOutlet 将永远不会被触发,从而导致什么都不会发生。

要设置 detailRef,请将其放入组件代码 (my-wrapper.component.ts):

import { ContentChild, TemplateRef } from '@angular/core';

@Component({ ... })
export class MyWrapperComponent {
    @ContentChild(TemplateRef) detailRef;

    ...
}

现在,您可以像这样使用包装器:

<my-wrapper>
    <ng-template>
        <my-component></my-component>
    </ng-template>
</my-wrapper>

我不确定为什么它需要如此复杂的“解决方法”,而过去在 AngularJS 中这样做很容易。

关于html - 当 ngIf 为 false 时构建 Angular4 ng-content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44929726/

相关文章:

node.js - 平均值 : nodejs server for Angular App - How do i serve angular routes

angular - 如何在 Angular 中从同级组件导航到另一个同级组件?

javascript - 如果 "webpage not found"则重定向到不同页面?

javascript - 使用 jQuery 获取当前事件处理程序的值

jquery - 使用 jquery 和 style 标签创建一个 div

Angular 2,无法从另一个组件访问一个组件中的变量

typescript - 如何使用通用对象和键类型作为字典中的键

angular - 可以从异步管道调用类方法吗?

typescript - 如何正确声明 typescript 中的类型

javascript - 在已经更改默认光标之后更改指针