MST

星途 面试题库

面试题:Angular响应式表单中如何验证输入框必填且格式为邮箱

在Angular响应式表单开发中,假设有一个输入框用于输入邮箱,请阐述如何通过代码实现该输入框必填,并且输入格式必须为邮箱格式的验证逻辑,需给出关键代码片段。
25.1万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 在组件类中定义表单控件并添加验证器
    import { Component } from '@angular/core';
    import { FormControl, Validators } from '@angular/forms';
    
    @Component({
      selector: 'app - email - form',
      templateUrl: './email - form.component.html',
      styleUrls: ['./email - form.component.css']
    })
    export class EmailFormComponent {
      emailControl = new FormControl('', [Validators.required, Validators.email]);
    
      getEmailErrorMessage() {
        if (this.emailControl.hasError('required')) {
          return '你必须输入一个值';
        }
    
        return this.emailControl.hasError('email')? '输入的邮箱格式不正确' : '';
      }
    }
    
  2. 在模板中使用该表单控件
    <form>
      <input type="email" [formControl]="emailControl">
      <div *ngIf="emailControl.hasError('required') && (emailControl.touched || emailControl.dirty)">
        {{getEmailErrorMessage()}}
      </div>
      <div *ngIf="emailControl.hasError('email') && (emailControl.touched || emailControl.dirty)">
        {{getEmailErrorMessage()}}
      </div>
    </form>
    

在上述代码中:

  • 在组件类中,使用FormControl创建了emailControl表单控件,并通过Validators.requiredValidators.email添加了必填和邮箱格式验证。
  • getEmailErrorMessage方法用于根据验证结果返回相应的错误信息。
  • 在模板中,通过[formControl]绑定表单控件,并使用*ngIf指令根据验证状态显示错误信息。只有当控件被触摸(touched)或值发生变化(dirty)时,才显示错误信息。