【发布时间】:2017-04-09 05:01:33
【问题描述】:
我有一个使用内容投影的扩展器。扩展器内容被包装到 *ngIf 中(用于性能优化)。不幸的是,我意识到我在可扩展对象中的所有指令在应用程序启动时都会被初始化,即使可扩展对象最初是关闭的。
我的指令不能在可扩展文件实际打开之前初始化。所以要么我需要某种初始化延迟,要么需要一个在实际呈现指令时触发的钩子。
示例代码(此处为 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
【问题讨论】:
-
不要将 angularjs 标签用于与 angular2 相关的问题,除非您的问题与这两个框架都有关,例如迁移问题。这是两个不同的框架,尽管有一个共同的名称。
标签: angular