【问题标题】:Angular template-driven form-validation using a directive使用指令的 Angular 模板驱动的表单验证
【发布时间】:2018-07-10 21:42:18
【问题描述】:

我一直在检查表单验证基础at the official docs,但我无法用其中一个示例来解决问题。

一些背景:

在此示例中,禁止使用的名称是“bob”,因此验证器将 拒绝任何包含“bob”的英雄名称。在其他地方它可以拒绝 "alice" 或配置正则表达式匹配的任何名称。

这里是输入元素:

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

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

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

如何让模板驱动的表单以反应式形式显示警报?

以下是官方文档中的示例:https://stackblitz.com/angular/byyynkdrode

提前致谢!

【问题讨论】:

    标签: angular


    【解决方案1】:

    必须

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

    【讨论】:

    • 5 分钟前想通了,我正要自己回答。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多