gpt4 book ai didi

javascript - 将 Angular 的 `useExitsing` 与自定义表单验证一起使用?

转载 作者:太空狗 更新时间:2023-10-29 17:58:38 25 4
gpt4 key购买 nike

阅读有关 adding custom validators to template-driven forms 的 Angular 文档
— 那里有一个简单的示例,用于自定义验证输入:

  • 需要
  • 最小长度="4"
  • 值不应包含“bob”

标记:

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

指令:

@Directive({
selector: '[appForbiddenName]',
providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective implements Validator {
@Input('appForbiddenName') forbiddenName: string;

validate(control: AbstractControl): {[key: string]: any} {
...
}
}

代码非常清晰。 但是他们也在那里说:

You may have noticed that the custom validation directive is instantiated with useExisting rather than useClass. The registered validator must be this instance of the ForbiddenValidatorDirective—the instance in the form with its forbiddenName property bound to “bob". If you were to replace useExisting with useClass, then you’d be registering a new class instance, one that doesn’t have a forbiddenName.

现在 — 我知道 useExistinguseValue 之间有什么区别。

但是他们在谈论哪个现有实例?如果 useExistsing 没有找到匹配项,它会创建一个 ...那么?

另外,注册一个新的类实例怎么会没有 forbiddenName 呢?它是其中的一个属性!

问题:

我不明白这里发生的操作顺序是什么。
谁在创建第一个实例,稍后由带有 useExisting 的指令代码使用?

(在某种程度上,如果我改用 useClass,它将创建另一个不包含该属性的实例....(???))

The online demo

最佳答案

ForbiddenValidatorDirective 实例只会在您的组件中使用时创建。 useExisting 只会确保使用确切的实例它保留了 @Input 字段。

I don't understand what is the sequence of operations that occur here.

  1. 当 Angular 检测到 appForbiddenName 在您的组件中使用时,创建了一个 ForbiddenValidatorDirective 实例(带有 @Input 字段)。
  2. Angular 在创建 form 指令实例时尝试注入(inject) NG_VALIDATORS(检测到 form 指令)。

in a way that If I use useClass instead , it will create another instance which doesn't contain the property....(???)

对于 useClass,Angular 只会将 ForbiddenValidatorDirective 视为普通类,并通过 new ForbiddenValidatorDirective() 创建一个实例,而 @输入将在这里被忽略。


在理解提供者NG_VALIDATORSuseExisting时,我们应该寻找它被注入(inject)的地方,参见here第一的。

NG_VALIDATORS 被注入(inject)到 form 指令中,以便在验证表单时调用。如下所述,这里必须使用 useExisting 才能得到 forbiddenName 它只存在于使用该指令创建的实例上,否则@Input 字段将是未定义的。

The registered validator must be this instance of the ForbiddenValidatorDirective—the instance in the form with its forbiddenName property bound to “bob". If you were to replace useExisting with useClass, then you’d be registering a new class instance, one that doesn’t have a forbiddenName.

关于javascript - 将 Angular 的 `useExitsing` 与自定义表单验证一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49003757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com