在我们的 angular 应用程序中,我们希望每个表单有大量的输入字段。我们已经实现了自定义输入组件,每个组件负责处理一个输入字段并使用反应式表单显示相应的错误消息。
虽然我们意识到将表单组划分为更小的组和数组的可能性,但我们希望为表单的最小部分提供有效的解决方案。
我想问一下,与下面演示的解决方案相比,是否有更好的方法(例如在渲染时间和减少不必要的更改检测方面)来实现我们的目标。
当前解决方案:
自定义输入组件有一个 @Input 字符串,它指定了 formControlName 以在通过 viewProvider 使用现有 FormGroupDirective 的帮助下将表单控件绑定到输入。
在自定义组件中,我们还有“@ViewChild(FormControlName) 控件”,它绑定到 FormControl 并在必要时用于检查有效性和错误输出。
一个最小的例子是:
parent.component.ts :
exampleForm = this.formBuilder.group({
exampleControl1: [null,Validators.required],
exampleControl2: [null,Validators.required]});
parent.component.html :
<form [formGroup]="patientForm">
<app-inputtype1-component>Label-String 1</app-inputtype1-component>
<app-inputtype2-component>Label-Stirng 2</app-inputtype2-component>
</form>
inputtype1.component.ts :
@Component({
selector: 'app-inputtype1',
templateUrl: './inputtype1.component.html',
styleUrls: ['./inputtype1.component.scss'],
viewProviders: [{provide: ControlContainer, useExisting: FormGroupDirective}]
})
export class Inputtype1Component implements OnInit, AfterViewInit {
@Input() stamp = '';
// @ts-ignore
@ViewChild(FormControlName) control;
constructor(public fgd: FormGroupDirective, private cdr: ChangeDetectorRef) {
}
ngOnInit() {
}
ngAfterViewInit() {
this.cdr.detectChanges();
}
}
inputtype1.component.html :
<label class="label">
<ng-content></ng-content>
</label>
<input type="text" id="{{stamp}}" class="input" formControlName="{{stamp}}"/>
<app-errors *ngIf="control?.invalid" [errors]="control.errors"></app-errors>
提前感谢您的任何意见!