当以角度处理表单时,通常的方法是将表单元素(如输入)直接放在表单中
<form>
<input>
</form>
当提交此表单并且输入具有验证器时,例如。必需的。表单输入经过验证,如果它无效,我们可以向用户展示......太好了......
为了能够重用自定义输入,我们可以创建一个包含此输入 + 附加内容的组件。
<form>
<custom-component>
</form>
检查这个堆栈闪电战:https ://stackblitz.com/edit/components-issue-whxtth?file=src%2Fapp%2Fuser%2Fuser.component.html
当点击提交按钮时,只有一个输入被验证。如果您与两个输入进行交互,它们将验证
就我在 CVA 组件中看到的而言,没有什么奇怪的。
@Component({
selector: "user",
templateUrl: "./user.component.html",
styleUrls: ["./user.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent implements ControlValueAccessor {
constructor(@Optional() @Self() public ngControl: NgControl) {
if (this.ngControl != null) {
// Setting the value accessor directly (instead of using the providers) to avoid running into a circular import.
this.ngControl.valueAccessor = this;
}
}
onTouched = (_value?: any) => {};
onChanged = (_value?: any) => {};
writeValue(val: string): void {}
registerOnChange(fn: any): void {
this.onChanged = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}