gpt4 book ai didi

Angular ControlValueAccessor 和 markAsTouched

转载 作者:行者123 更新时间:2023-12-03 16:49:03 29 4
gpt4 key购买 nike

我将 Angular 9 与 Angular Material 一起使用,并且通过实现 ControlValueAccessor 接口(interface)来自定义控件。一切正常。

当表单无效时,在我的所有提交按钮中,我调用 formGroup.markAllAsTouched 因为所有 Angular Material 字段都变为红色。通过这种方式,用户可以更好地了解哪些控件无效。

我需要用我的自定义控件实现相同的行为。怎么做?

为了更好地了解情况,我创建了一个 stackblitz 项目 here

最佳答案

no built-in functionality用于传播touched状态到自定义控件的内部 FormControl。

您的简单选择是检查 ngDoCheck 中的状态并且一旦自定义控件被触及,内部 FormControl 的更新状态:

ngDoCheck() {
if (this.formControl.touched) {
return;
}
if (this.controlDir.control.touched) {
this.formControl.markAsTouched();
}
}

Forked Stackblitz

就个人而言,我不喜欢 ControlValueAccessor 的这种实现。 .
我宁愿使用相同的 FormControl。这可以通过添加 viewProviders 来完成与 ControlValueAccessor您的自定义控件的提供程序:

custom-control.component.ts
@Component({
selector: 'my-custom-control',
template: `
<mat-form-field id="userType">
<mat-label>My Custom Component</mat-label>
<mat-select [formControlName]="controlName" (blur)="onTouched()">
<mat-option *ngFor="let current of userTypes" [value]="current.id">{{current.name}}</mat-option>
</mat-select>
</mat-form-field>

`,
viewProviders: [{
provide: ControlContainer,
useFactory: (container: ControlContainer) => container,
deps: [[new SkipSelf(), ControlContainer]],
}]
})
export class MyCustomControl {
@Input() controlName: string;

userTypes: LookupModel[] = [
new LookupModel(1, 'first'),
new LookupModel(2, 'second')
];
}

父 html
<form [formGroup]="form">
<my-custom-control controlName="userTypeCustomControl"></my-custom-control>

Stackblitz Example

关于Angular ControlValueAccessor 和 markAsTouched,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61566769/

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