模板驱动形式的自定义验证器总是 returns null

Custom validator in template driven form always returns null

我正在尝试以模板驱动的形式添加自定义验证器。我正在使用 Angular 7。无论值是多少,我总是得到 null。

HTML:

<div class="form-group">
  <label style="font-weight:bold">Seats Available</label> <input type="number" required class="form-control" [(ngModel)]="seats" name="carseat" #carseat="ngModel" validateseat />
  <div *ngIf="carseat.dirty && carseat.errors?.validseat">Required.</div>
</div>

代码:

import { Validator, FormControl } from "@angular/forms";
import { Directive } from "@angular/core";

@Directive({
  selector: "[validateseat]"
})
export class Seatvalidatordirective implements Validator {
  validate(control: FormControl): { [key: string]: any } | null {
    console.log("dd", control.value);
    return control.value < 0 || control.value > 8 ? { validseat: true } : null;
  }
}

您实际上并没有提供自定义验证器,您需要添加:

providers: [
  { provide: NG_VALIDATORS, useExisting: Seatvalidatordirective, multi: true }
]

您的指令:

@Directive({
  selector: "[validateseat]",
  providers: [
    { provide: NG_VALIDATORS, useExisting: Seatvalidatordirective, multi: true }
  ]
})
export class Seatvalidatordirective implements Validator {
  validate(control: FormControl): { [key: string]: any } | null {
    console.log("dd", control.value);
    return control.value < 0 || control.value > 8 ? { validseat: true } : null;
  }
}

这里是StackBlitz