Angular 异步验证器发送到 Dumb 组件

问题描述 投票:0回答:1

您在 Dumb 组件中定义 FormGroup 以将相关数据保存在一起。然后,您需要在某些表单控件上使用异步验证器,但哑组件不应该有服务调用。一种选择是将 AsyncFn 作为 Input() 发送。你会如何处理这个问题?

dumb.component.ts

export class AddEditNameComponent {
  @Input() form: FormGroup;
  @Input() nameAlreadyExistsValidator: AsyncValidatorFn;

  ngOnInit(): void {
    this.form = this.initFormGroup();
  }

  private initFormGroup() {
    return new FormGroup({
      id: new FormControl(0),
      name: new FormControl('', [Validators.required], [this.nameAlreadyExistsValidator]),
    });
  }
}
angular typescript validation asynchronous angular-components
1个回答
0
投票

你是对的。在这种情况下,您可以在可能到达必要服务的地方定义验证器函数,然后将其传递给哑组件。只是不要忘记

.bind(this)
,因为形式总是会丢失它。您也可以随时参考官方文档

© www.soinside.com 2019 - 2024. All rights reserved.