英文:
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: '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) {
}
}
Then, in your template, you can use it like this:
<span *ngIf="control.hasError('max')">
Max {{ control.getError('max').max }} allowed
</span>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论