【问题标题】:Directive @Input variable not getting update when component update the value当组件更新值时,指令@Input 变量没有得到更新
【发布时间】:2020-04-03 01:31:04
【问题描述】:

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

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

EventObservable:

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

模板:

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

【问题讨论】:

  • 问题不是没有收到新的值。如果您使用 setter 或 ngOnCHanges,您可以轻松地检查它。问题是你希望 validate 方法被再次调用,即使表单控件的值没有改变。

标签: angular typescript angular-directive


【解决方案1】:

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

onChange: () => void;

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

ngOnChanges(changes: SimpleChanges): void {
  if ('available' in changes) {
    if (this.onChange) {
      this.onChange();
    }
  }
}

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

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

【讨论】:

  • 我今天学到了一些东西,谢谢。当您想以反应形式简单地将验证器添加到 FormControl 并希望验证器在除 FormCOntrol 值之外的其他内容发生变化时重新验证(显式重新验证除外)时,是否有一些类似的机制可用?
  • 不确定抱歉,我只使用模板表单。
  • 感谢@AdrianBrand
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2017-06-19
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 2014-08-06
相关资源
最近更新 更多