2016-06-10 34 views
2

我有一个指令可以在模型上执行任务,但是我在运行outcommented循环之前等待值为真时出现问题,应确定指令在首次启动指令时是否应具有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; 
     } 
    }); 
    } 
} 

回答

3

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; 
     } 
    } 

    } 
} 
+0

已经说ngOnInit没有工作,虽然 – Chrillewoodz

+0

对不起,错过了。任何信息为什么不起作用?如果你想在输入设置的时候做一些事情,那么这两条就是要走的路。也许问题在别的地方? –

+0

我有一个核心组件,它只包含一些虚拟数据atm,它是一个对象数组。我将这个数组传递给指令,但它说,当我尝试运行循环时,它不能读取未定义的'.length':/ – Chrillewoodz

相关问题