gpt4 book ai didi

angular - 投影 Angular Directive(指令)在应该隐藏时被初始化

转载 作者:太空狗 更新时间:2023-10-29 19:35:06 26 4
gpt4 key购买 nike

我有一个使用内容投影的扩展器。扩展器内容被包装到 *ngIf 中(用于性能优化)。不幸的是,我意识到我在可扩展项中的所有指令都在应用程序启动时被初始化,即使可扩展项最初是关闭的。

我的指令不得在实际打开可扩展项之前初始化。因此,要么我需要某种初始化延迟,要么需要一个在实际呈现指令时触发的 Hook 。

示例代码(此处为 Plunker:https://plnkr.co/edit/R84AXZheAtZYLRmeSfkm?p=preview):

@Component({
selector: 'my-app',
template: `
<some-component>
Projected content <div some-directive></div>
</some-component>
`,
})
export class App {}


//************* Component that uses content projection *************

@Component({
selector: 'some-component',
template: `
<button (click)="showBody=!showBody">Toggle Content</button>
<div *ngIf="showBody">
<ng-content></ng-content>
</div>
`,
})
export class SomeComponent {
constructor() {}
private showBody = false;
}

//************* Directive that is set within an ng-if *************
@Directive({
selector: '[some-directive]',
})
export class SomeDirective {
constructor() {
}

ngOnInit() {
document.body.append('This should not be executed when the content is not visible');
}
}

Plunker 可以在这里找到:https://plnkr.co/edit/R84AXZheAtZYLRmeSfkm?p=preview

最佳答案

更新 Angular 5

ngOutletContext已重命名为 ngTemplateOutletContext

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

原创

这是预期的行为。您可以在没有 <ng-content> 的情况下投影内容并使用 @ContentChildren() 查询它.

您需要另一种策略。例如将内容作为模板传递并使用 ngTemplateOutlet插入内容

另见 How to repeat a piece of HTML multiple times without ngFor and without another @Component

关于angular - 投影 Angular Directive(指令)在应该隐藏时被初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40794056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com