2017-09-22 17 views
4

2つのコントロールに値があるかどうかを調べるために、Angularでディレクティブを作成しました。それらのうちの1つが満たされている場合、もう1つは満たされなければならないので、それらは空でも両方とも満たされなければならない。今のところうまくいきます。角度 - ディレクティブの入力がボタンを押しても更新されない

このディレクティブは、デフォルトで無効にする必要があります。ボタンを押した後で有効にする必要があります。これを制御するには、私は、変数をバインドするディレクティブで@Inputを持つ「真」にボタンセット:

import { Validator, FormControl, NG_VALIDATORS, FormGroup, NgForm } from '@angular/forms'; 
import { Directive, forwardRef, Input, ElementRef } from '@angular/core'; 

@Directive({ 
    selector: '[correquired][ngModel]', 
    providers: [ 
     { provide: NG_VALIDATORS, useExisting: forwardRef(() => CorrequiredDirective), multi: true } 
    ] 
}) 
export class CorrequiredDirective implements Validator { 
    @Input() other: FormControl; 
    @Input() enabled: boolean; 

    validate(c: FormControl): { [index: string]: any; } { 
     if (!this.enabled) { return null; } 

     if (this.other != null && this.other.value != null && this.other.value.trim && this.other.value.trim() === '') { 
     this.other.setValue(null); 
     } 

     if (c.value != null && c.value.trim && c.value.trim() === '') { 
      c.setValue(null); 
     } 

     if (c.value != null && c.value != undefined) { 
      this.other.markAsTouched(); 
     } 

     if (this.other != null && c.value == null && this.other.value != null) { 
      return { 'correquired': { valid: false } }; 
     } 
    } 
} 

そして、コンポーネントで、私はコントロールを設定し、この方法:

<input type="text" correquired [other]="form3.controls['delivered_quantity']" [enabled]="publishing" ... 

変数「公開」をtrueに設定するボタンもフォームを送信します。問題は、このボタンを押すと、 "publishing"の値を変更する前にディレクティブが実行されていることです。ディレクティブの "enabled"変数は常にfalseです。ボタンを押したときにどうすれば更新できますか?

ありがとうございます。 trueに変数を設定するとき

答えて

0

[OK]を、私は、ボタンによって呼び出されるメソッドでのsetTimeoutを追加することによって、それを解決することができます:

publish() {   
    this.publishing = true;  

    setTimeout(() => { 
     if (this.form3.control.controls['delivered_quantity'] != null) { 
      this.form3.control.controls['delivered_quantity'].updateValueAndValidity(); 
     } 
     if (this.form3.control.controls['delivered_no'] != null) 
      this.form3.control.controls['delivered_no'].updateValueAndValidity(); 
     if (this.formsValid && this.radioForm.valid) { 
      if (this.formsDirty) { 
       this.doSave() 
        .add(() => { 
         this.doPublish(); 
        }); 
      } else { 
       this.doPublish(); 
      } 
     } 
    }, 0); 
} 
関連する問題