在 Angular 中使用带有模板数组的 FormBuilder.group() 时如何添加验证器?
How to add Validators, when using FormBuilder.group() with an template array in Angular?
我正在尝试构建一个表单,该表单在一个数组中定义输入字段,如下所示:
export const FormTemplate = [
//contact
{
name: '',
lastname: '', //required
email: '', //required, valid
phone: '',
},
并且我想向字段 'lastname' 和 'email' 添加验证器。
我的 .ts 文件如下所示:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormGroup, FormArray, Validators} from '@angular/forms';
import { throwError } from 'rxjs';
import { saveAs } from 'file-saver'
import { FormTemplate } from './form-template'
@Component({
selector: 'app-request-form',
templateUrl: './request-form.component.html',
styleUrls: ['./request-form.component.sass']
})
export class RequestFormComponent implements OnInit {
formTemplate = FormTemplate;
contactForm: FormGroup;
submitData;
url = 'http://localhost:3000/';
constructor(
private fb: FormBuilder,
private http: HttpClient
) { }
ngOnInit(): void {
this.contactForm = this.fb.group(this.formTemplate[0],{
validator: Validators.compose([
Validators.email,
Validators.required
])
});
}
submitToServer(){
this.submitData = [
this.contactForm.value,
this.addressForm.value,
this.companyForm.value,
];
var mediaType = 'application/pdf';
this.http.post(this.url, this.submitData, {responseType: 'blob'}).subscribe(
(response) =>{
var blob = new Blob([response], {type: mediaType});
//saveAs(blob, 'name.pdf');
},
e => {
alert(e.message)
throwError(e);}
)
}
get email(){
return this.contactForm.get('email');
}
这是我的 html:
<mat-horizontal-stepper>
<mat-step>
Value:{{contactForm.value | json}}
<form [formGroup]="contactForm" class="contact">
<mat-form-field>
<input matInput placeholder="name" formControlName="name" class="input">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="lastname" formControlName="lastname">
</mat-form-field>
<mat-form-field>
<input type="email" matInput placeholder="email" formControlName="email">
<mat-error *ngIf="email.invalid && email.touched">
Email looks wrong
</mat-error>
</mat-form-field>
<mat-form-field>
<input type="tel" matInput placeholder="phone" formControlName="phone">
</mat-form-field>
</form>
<div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button matStepperNext>Next</button>
</div>
</mat-step>
我想使用用作模板的数组,因为我不想在我的 .ts 文件中定义每个输入字段。但是当我想使用验证器时没有其他方法吗?
提前致谢
这可能有效-
this.contactForm = this.fb.group(this.formTemplate[0],
{ validators: [Validators.required,Validators.email] }
});
我找到了获得预期结果的方法
这就是我的模板 .ts 现在的样子:
import {Validators} from '@angular/forms';
export const FormTemplate = [
//contact
{
name: '',
lastname: ['',[
Validators.required
]],
email: ['',[
Validators.required,
Validators.email
]],
phone: '',
},
这是我的 component.ts 文件:
ngOnInit(): void {
this.contactForm = this.fb.group(this.formTemplate[0]);
}