如何自定义表单控件获取验证值?

huangapple go评论52阅读模式
英文:

How a custom form control can get a validation value?

问题

我正在开发一个自定义表单控件,也就是一个实现了 ControlValueAccessor 接口的组件,以便与 Angular 表单 API 一起使用。

该组件有一些验证逻辑。例如,使用了 Validators.max 及其值。我的意图是,如果验证失败,组件将显示一个带有正确值的错误消息。

然而,要显示这个消息,组件需要知道最大值。所以,我的问题是如何传递它?是 @Input() 是唯一的选项,还是表单 API 提供了另一种更清晰的方式来处理这种情况?

英文:

I am working on a custom form control, that is, a component that implements the ControlValueAccessor interface in order to be used along with the Angular forms API.

There is some validation logic for that component. For example, Validators.max with its value is in use. My intention is if the validation fails the component would show an error message with the right value.

However, to show this message the component needs to know the max value. So, my question is how can I pass it? Is @Input() the only option or the forms API provides another, more clear, way for this sort of situations?

答案1

得分: 1

你可以将关联的表单控件注入到你的组件构造函数中,像这样:

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss'],
  providers: [ ... ]
})
export class MyComponent implements ControlValueAccessor {

  // . . .

  get control(): FormControl {
    return this.ngControl?.control as FormControl;
  }

  constructor(@Optional() @Self() public ngControl: NgControl) {
  }
}

然后,在你的模板中,你可以像这样使用它:

<span *ngIf="control.hasError('max')">
    最大值 {{ control.getError('max').max }} 允许
</span>
英文:

You can inject the associated form control into your component constructor, like this:

@Component({
  selector: &#39;my-component&#39;,
  templateUrl: &#39;./my.component.html&#39;,
  styleUrls: [&#39;./my.component.scss&#39;],
  providers: [ ... ]
})
export class MyComponent implements ControlValueAccessor {

  // . . .

  get control(): FormControl {
    return this.ngControl?.control as FormControl;
  }

  constructor(@Optional() @Self() public ngControl: NgControl) {
  }
}

Then, in your template, you can use it like this:

&lt;span *ngIf=&quot;control.hasError(&#39;max&#39;)&quot;&gt;
    Max {{ control.getError(&#39;max&#39;).max }} allowed
&lt;/span&gt;

huangapple
  • 本文由 发表于 2023年4月20日 04:15:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定