gpt4 book ai didi

angular - NG_VALIDATORS 和验证器的区别(类)

转载 作者:太空狗 更新时间:2023-10-29 18:08:13 25 4
gpt4 key购买 nike

我对 NG_VALIDATORS 的用途感到困惑,我知道它是一个提供商 token 。但是它有什么用呢?它有什么不同的表单验证器类?

https://github.com/angular/angular/blob/4.3.3/packages/forms/src/validators.ts

最佳答案

您有两种方法可以将验证器添加到表单控件。通过将它们指定为表单控件的参数来使用命令式方法:

const ctrl = new FormControl('', Validators.required);

或通过在模板中使用验证器特定指令以声明方式:

<input [formControl]='ctrl' required>

NG_VALIDATORS token 用于第二种情况。这些 token 由验证器指令 requiredemail 和其他指令定义。它们定义在由表单指令创建的注入(inject)器上 - NgFormNgModelNgModelGroup。参见 How exactly works the services hierarchy in this Angular 2 application?了解有关创建自己的注入(inject)器的指令的更多信息。

所有内置和自定义验证器都使用此 token 注册:

export const EMAIL_VALIDATOR: any = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => EmailValidator),
multi: true
};
@Directive({
selector: '[email]...',
providers: [EMAIL_VALIDATOR] <-------------
})
export class EmailValidator implements Validator {

export const REQUIRED_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => RequiredValidator),
multi: true
};
@Directive({
selector:
'[required]...',
providers: [REQUIRED_VALIDATOR], <-------------
})
export class RequiredValidator implements Validator {

Angular 响应式(Reactive)和模板驱动的表单指令(NgFormNgModelNgModelGroup)使用此 token 注入(inject)验证器:

export class NgForm extends ControlContainer implements Form {
...
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],

export class NgModel extends NgControl implements OnChanges,
...
constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators...,

export class NgModelGroup extends AbstractFormGroupDirective implements ... {
...
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],

NG_ASYNC_VALIDATORS token 也是如此。

关于angular - NG_VALIDATORS 和验证器的区别(类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45552590/

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