面试题答案
一键面试设计思路
- 状态管理:使用RxJS的BehaviorSubject来管理表单的当前步骤和全局验证状态。BehaviorSubject可以保存当前值,并将其发射给新的订阅者,便于在不同组件间共享状态。
- 动态验证规则:根据第一步的选择(个人用户或企业用户),动态生成后续步骤的验证规则。可以将验证规则定义为函数,根据条件动态绑定到表单控件上。
- 性能优化:采用懒加载的方式加载不同步骤的表单组件,避免一次性加载所有组件导致的性能问题。同时,使用OnPush变更检测策略,减少不必要的组件检查。
关键代码架构
- 创建表单状态管理服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FormStateService {
private currentStepSubject = new BehaviorSubject<number>(1);
currentStep$ = this.currentStepSubject.asObservable();
private userTypeSubject = new BehaviorSubject<string>('');
userType$ = this.userTypeSubject.asObservable();
constructor() {}
setCurrentStep(step: number) {
this.currentStepSubject.next(step);
}
setUserType(type: string) {
this.userTypeSubject.next(type);
}
}
- 第一步表单组件
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { FormStateService } from '../services/form-state.service';
@Component({
selector: 'app-step1',
templateUrl: './step1.component.html',
styleUrls: ['./step1.component.css']
})
export class Step1Component {
step1Form: FormGroup;
constructor(private formStateService: FormStateService) {
this.step1Form = new FormGroup({
userType: new FormControl('', Validators.required)
});
}
onSubmit() {
const userType = this.step1Form.get('userType').value;
this.formStateService.setUserType(userType);
this.formStateService.setCurrentStep(2);
}
}
- 后续步骤表单组件
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { FormStateService } from '../services/form-state.service';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-step2',
templateUrl: './step2.component.html',
styleUrls: ['./step2.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Step2Component {
step2Form: FormGroup;
constructor(private formStateService: FormStateService) {
this.step2Form = new FormGroup({});
this.formStateService.userType$.pipe(
map(userType => {
if (userType === '个人用户') {
return {
personalField: new FormControl('', Validators.required)
};
} else {
return {
companyField: new FormControl('', Validators.required)
};
}
})
).subscribe(controls => {
this.step2Form = new FormGroup(controls);
});
}
}
- 路由懒加载
在
app-routing.module.ts
中配置懒加载
const routes: Routes = [
{ path:'step1', loadChildren: () => import('./step1/step1.module').then(m => m.Step1Module) },
{ path:'step2', loadChildren: () => import('./step2/step2.module').then(m => m.Step2Module) }
];
通过以上架构,我们可以实现一个灵活且高效的表单验证架构,能够应对多步骤向导式表单中复杂的验证需求。