面试题答案
一键面试实现思路
- 事件发射器(@Output):在子组件中,使用
@Output
装饰器定义一个事件发射器,当表单验证出错时,通过该事件发射器将错误信息发射出去。父组件可以监听这个事件来获取错误信息。 - 服务(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();
}
}