当组件更新值时,指令@Input 变量未得到更新

Dar*_*nce 3 typescript angular-directive angular

我正在尝试根据服务调用结果动态验证自定义文本输入。如果它是真的意味着 jumpyId 可以使用,否则显示错误。我现在的问题是当我从 fromEvent 更新 this.isAvailable 时,它​​没有反映自定义指令中的值。我期待如果 api 调用返回true,则指令应该接收true否则false

可用指令.ts

import { Directive, forwardRef, Input } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
@Directive({
  selector: 'custom-text-input[vendorAvailable][formControlName],custom-text-input[vendorAvailable][formControl],custom-text-input[vendorAvailable][ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: AvailabilityDirective, multi: true }
  ]
})
export class AvailabilityDirective implements Validator {

  @Input('available') available: boolean;
  validate(c: AbstractControl): { [key: string]: any } {
    console.log("valid", this.available);
    if (!this.available) {
      return {
        available: false
      };
    }
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

事件观察:

fromEvent(this.custom.nativeElement, 'keyup').pipe(
      map((event: any) => {
        return event.target.value;
      })
      , debounceTime(1000)
      , distinctUntilChanged()
    ).subscribe((text: string) => {
      this.myService.isAvailable(text).subscribe((res) => {
        console.log(res);
        if (res) {
          this.isAvailable = true;
        } else {
          this.isAvailable = false;
        }
      }, (err) => {
        console.log(err);
      });
    });
Run Code Online (Sandbox Code Playgroud)

模板:

<custom-text-input *ngIf="drawer"
                                           label="JumpyId"
                                           [(ngModel)]="jumpyId"
                                           id="jumpyId"
                                           name="jumpyId"
                                           required
                                           [available]="isAvailable"
                                           #custom>
                        </custom-text-input>
Run Code Online (Sandbox Code Playgroud)

Adr*_*and 6

添加一个监视可用更改的 onChanges

onChange: () => void;

registerOnValidatorChange(fn: () => void): void {
  this.onChange = fn;
}

ngOnChanges(changes: SimpleChanges): void {
  if ('available' in changes) {
    if (this.onChange) {
      this.onChange();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我的验证指令依赖于另一个输入,我使用这个验证器基础

https://stackblitz.com/edit/angular-cfexiy