如何在执行任务之前等待绑定获取其值

How to wait for a binding to get its value before performing a task

我有一个在模型上执行任务的指令,但是在 运行 取消注释掉的循环之前等待值变为真时我遇到了问题,它应该决定指令是否应该首次启动指令时具有 truefalse 值的状态。

我能想到的唯一解决方案是使用 ngDoCheck 但是一旦 this.model 完全具有它的价值,我就找不到解决这个问题的方法解决。

我不希望它 运行 在我完成启动后。我也尝试使用 ngOnInitAfterViewInit 但这些显然对这件事没有帮助。

那么如何等待 this.model 获取它的值再执行任务呢?

import {Directive, ElementRef, Renderer} from '@angular/core';

@Directive({
  selector: '[checkAll]',
  inputs: [
    'model'
  ]
})

export class CheckAllDirective {

  constructor(private _elementRef: ElementRef, private _renderer: Renderer) {

    // TODO: Need to wait for this.model to set before performing this
    // for (let checkbox of this.model) {
    //
    //   if (checkbox.isChecked) {
    //     this.isAllChecked = true;
    //   }
    //   else {
    //     this.isAllChecked = false;
    //   }
    // }

    this.eventHandler = _renderer.listen(_elementRef.nativeElement, ('ontouchstart' in window ? 'touchend' : 'click'), (e) => {

      this.isAllChecked = !this.isAllChecked;

      for (let checkbox of this.model) {
        checkbox.isChecked = this.isAllChecked;
      }
    });
  }
}
每次更新输入后都会调用

ngOnChanges

ngOnInitngOnChanges 第一次被调用后被调用。

export class CheckAllDirective {

  constructor(private _elementRef: ElementRef, private _renderer: Renderer) {

  }

  ngOnInit() {
     for (let checkbox of this.model) {

       if (checkbox.isChecked) {
         this.isAllChecked = true;
       }
       else {
         this.isAllChecked = false;
       }
     }

  }
}