我已经创建了一个Angular表单,我想验证输入。此行应验证地址:
<span *ngIf='submitted && f.caddress.errors' class="invalid-feedback">Customer address is required!</span>
但我发现了这个错误:
属性"cadress"来自索引签名,因此必须使用["address"]访问它
这是.ts文件:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
customerForm!:FormGroup;
submitted =false;
constructor(
private formbuilder:FormBuilder,
private route: ActivatedRoute,
private router:Router
) { }
ngOnInit(): void {
this.onSubmit();}
onSubmit() {
this.customerForm = this.formbuilder.group({
uname : ['', Validators.required],
cphone : ['', Validators.required],
caddress : ['', Validators.required]
})
}
get f(){
return this.customerForm.controls
}
submitCustomer(){
this.submitted = true;
if (this.customerForm.invalid){
return;
}
}
}
错误说明您想要做什么。您需要使用f[caddress].errors.required
而不是f.caddress.errors
FromGroup
控件内部的如下所示
controls: {
[key: string]: AbstractControl;
};
因此,当您引用formControlName
时,您需要使用this.customerForm.controls[caddress]
或this.customerForm.get('caddress')
你可以像这个this.customerForm.get('caddress').error.required
一样检查错误