【问题标题】:Projected angular directive gets initialized when it should be hidden投影的角度指令在应该隐藏时被初始化
【发布时间】: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


【解决方案1】:

更新 Angular 5

ngOutletContext 更名为ngTemplateOutletContext

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

原创

这是预期的行为。您可以在没有&lt;ng-content&gt; 的情况下拥有投影内容,并使用@ContentChildren() 对其进行查询。

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

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

【讨论】:

  • 感谢您的回复。我可以在指令中使用某种钩子以便在它被渲染时得到通知吗?
  • 指令本身在ngOnInit() 之后被渲染。我不确定是否为指令调用了 ngAfterViewInit(),但调用了 ngAfterContentInit() 并且应该这样做。
猜你喜欢
  • 2015-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 2019-07-19
相关资源
最近更新 更多