使用指令的 Angular 模板驱动的表单验证

标签 angular

我一直在检查表单验证基础知识 at the official docs我无法理解其中一个例子。

一些背景:

In this sample, the forbidden name is "bob", so the validator will reject any hero name containing "bob". Elsewhere it could reject "alice" or any name that the configuring regular expression matches.

这是输入元素:

<input id="name" name="name" class="form-control"
   required minlength="4" forbiddenName="bob"
   [(ngModel)]="hero.name" #name="ngModel" >

然而,他们示例中的输入似乎未经过验证:

enter image description here

虽然来自同一示例的使用响应式(Reactive)形式的输入按预期得到验证:

enter image description here

如何使模板驱动的表单以 react 形式显示警报?

这是来自官方文档的示例:https://stackblitz.com/angular/byyynkdrode

提前致谢!

最佳答案

必须是

<input id="name" name="name" class="form-control"
               required minlength="4" appForbiddenName forbiddenName="bob"
               [(ngModel)]="hero.name" #name="ngModel" >

<input id="name" name="name" class="form-control"
               required minlength="4" appForbiddenName [forbiddenName]="'bob'"
               [(ngModel)]="hero.name" #name="ngModel" >

看到指令名称是“appForbiddenName”,@Input 变量是“forbiddenName”。当然,您可以更改指令,并使选择器的名称与@Input 相同

@Directive({
  selector: '[forbiddenName]', //<--forbiddenName, NOT appforbiddenName
  providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective implements Validator {
  @Input() forbiddenName: string; //<--see that the input variable is the same
                                  //that the selector of the directive
  ....
}

关于使用指令的 Angular 模板驱动的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547947/

相关文章:

javascript - 如何创建表单下拉菜单 - Angular 2

javascript - 如何在 Angular 9 中访问组件的唯一封装 ID

javascript - Angular 2 的语义错误 typescript NgMatchers

angular - Ionic 3 ngrx/store reducer 仅在生产模式下不接收调度的操作

angular - Angular 的 NO_ERRORS_SCHEMA 有问题吗?

angular - 当我尝试从 Linux 中使用 ngserve 运行我的应用程序时,出现此错误 :Cannot find module '@angular-devkit/build-angular/package. json

angular - 面向列的垫子表

angular - Rxjs 管道不适用于 Angular 的 Http.get()

angular - 订阅 Angular 2 Http 两次?

css - Angular scss 不适用于 ngx-datatable