首页 文章

当隐藏角度指令被隐藏时,它会被初始化

提问于
浏览
3

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

在实际打开expandable之前,我的指令不能初始化 . 所以要么我需要某种初始化延迟,要么在实际呈现指令时触发一个钩子 .

示例代码(此处为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

1 回答

相关问题