MST

星途 面试题库

面试题:Angular中如何在跨组件间处理表单验证错误信息

假设存在一个复杂的Angular应用,表单分布在多个组件中,当某个子组件的表单验证出现错误时,如何在父组件或其他相关组件中有效地获取并处理这些错误信息,说明实现思路并给出核心代码片段。
41.5万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 事件发射器(@Output):在子组件中,使用@Output装饰器定义一个事件发射器,当表单验证出错时,通过该事件发射器将错误信息发射出去。父组件可以监听这个事件来获取错误信息。
  2. 服务(Service):创建一个共享服务,子组件在表单验证出错时将错误信息存入服务中。其他组件(包括父组件)通过注入该服务来获取错误信息。

核心代码片段

1. 使用 @Output

子组件(child.component.ts)

import { Component, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  myForm: FormGroup;
  @Output() formError = new EventEmitter<string>();

  constructor() {
    this.myForm = new FormGroup({
      'inputField': new FormControl('', Validators.required)
    });
    this.myForm.statusChanges.subscribe(status => {
      if (status === 'INVALID') {
        this.formError.emit('表单验证错误');
      }
    });
  }
}

父组件(parent.component.html)

<app-child (formError)="handleChildFormError($event)"></app-child>

父组件(parent.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  handleChildFormError(errorMessage: string) {
    console.log('子组件表单错误:', errorMessage);
    // 处理错误逻辑
  }
}

2. 使用服务

共享服务(error - service.ts)

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ErrorService {
  private formError: string | null = null;

  setFormError(error: string) {
    this.formError = error;
  }

  getFormError() {
    return this.formError;
  }
}

子组件(child.component.ts)

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ErrorService } from './error - service';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  myForm: FormGroup;

  constructor(private errorService: ErrorService) {
    this.myForm = new FormGroup({
      'inputField': new FormControl('', Validators.required)
    });
    this.myForm.statusChanges.subscribe(status => {
      if (status === 'INVALID') {
        this.errorService.setFormError('表单验证错误');
      }
    });
  }
}

其他组件(如父组件 parent.component.ts)

import { Component } from '@angular/core';
import { ErrorService } from './error - service';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  formError: string | null;

  constructor(private errorService: ErrorService) {
    this.formError = this.errorService.getFormError();
  }
}