在Angular 4中,可以通过使用FormGroup和FormControl来创建响应式表单。为了实现当一个字段失焦时将所有字段标记为红色,我们可以使用以下方法:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({
field1: new FormControl('', Validators.required),
field2: new FormControl('', Validators.required),
field3: new FormControl('', Validators.required),
});
}
}
export class FormComponent implements OnInit {
myForm: FormGroup;
field1Blurred: boolean = false;
field2Blurred: boolean = false;
field3Blurred: boolean = false;
onFieldBlur(field: string) {
switch (field) {
case 'field1':
this.field1Blurred = true;
break;
case 'field2':
this.field2Blurred = true;
break;
case 'field3':
this.field3Blurred = true;
break;
}
}
}
.red {
border-color: red;
}
这样,当一个字段失焦时,它会添加红色的边框,指示它是无效的。