面试题答案
一键面试- HTML 模板部分:
- 假设我们有一个输入框,并且使用了
required
和minlength
验证。
<input type="text" formControlName="myControl" /> <div *ngIf="myForm.get('myControl')?.hasError('required') && (myForm.get('myControl')?.touched || myForm.get('myControl')?.dirty)"> <span class="error - style">This field is required.</span> </div> <div *ngIf="myForm.get('myControl')?.hasError('minlength') && (myForm.get('myControl')?.touched || myForm.get('myControl')?.dirty)"> <span class="error - style">Minimum length not met.</span> </div>
- 假设我们有一个输入框,并且使用了
- CSS 样式部分:
.error - style { color: red; font - size: 14px; }
3. **TypeScript 部分(假设使用 reactive forms)**:
```typescript
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app - my - form',
templateUrl: './my - form.component.html',
styleUrls: ['./my - form.component.css']
})
export class MyFormComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
'myControl': new FormControl('', [Validators.required, Validators.minLength(5)])
});
}
}
在上述代码中:
- HTML 模板通过
*ngIf
指令判断表单控件是否有特定的验证错误,并且在控件被触摸或值发生改变后才显示错误信息。 - CSS 样式
.error - style
定义了错误信息的显示样式,如颜色为红色,字体大小为 14 像素。 - TypeScript 部分创建了一个 reactive 表单,并为表单控件添加了
required
和minlength
验证。