面试题答案
一键面试定义并触发自定义提交事件
- 在子组件中定义事件:
- 在子组件的
.ts
文件中,从@angular/core
导入EventEmitter
和Output
。 - 声明一个
Output
属性,类型为EventEmitter
。例如:
import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app - custom - form', templateUrl: './custom - form.component.html', styleUrls: ['./custom - form.component.css'] }) export class CustomFormComponent { @Output() customSubmit = new EventEmitter(); onSubmit() { // 在这里进行表单验证等逻辑 this.customSubmit.emit(); } }
- 在子组件的
- 在子组件模板中触发事件:
- 在表单的提交按钮或提交逻辑处调用触发函数。例如:
<form (ngSubmit)="onSubmit()"> <!-- 表单内容 --> <button type="submit">提交</button> </form>
- 在父组件中监听处理:
- 在父组件的模板中使用子组件,并监听自定义事件。例如:
<app - custom - form (customSubmit)="handleCustomSubmit()"></app - custom - form>
- 在父组件的
.ts
文件中定义处理函数:
import { Component } from '@angular/core'; @Component({ selector: 'app - parent - component', templateUrl: './parent - component.html', styleUrls: ['./parent - component.css'] }) export class ParentComponent { handleCustomSubmit() { console.log('自定义提交事件被触发'); // 处理提交后的逻辑 } }
双向绑定及性能优化
- ngModel性能优化:
- 使用
ChangeDetectionStrategy.OnPush
:- 在子组件的
@Component
装饰器中设置changeDetection
为ChangeDetectionStrategy.OnPush
。这会告诉Angular仅在输入属性引用改变或子组件触发事件时才运行变更检测。
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app - custom - form', templateUrl: './custom - form.component.html', styleUrls: ['./custom - form.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class CustomFormComponent { // 组件逻辑 }
- 在子组件的
- 减少不必要的更新:
- 确保
ngModel
绑定的变量只有在真正需要改变时才改变。例如,对于复杂对象,可以使用不可变数据模式,当对象的部分属性改变时,创建新的对象实例而不是直接修改原对象,这样可以避免Angular因引用未改变而未检测到变更的情况。 - 如果表单数据在特定条件下才需要更新,使用
NgZone
手动控制变更检测。例如:
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app - custom - form', templateUrl: './custom - form.component.html', styleUrls: ['./custom - form.component.css'] }) export class CustomFormComponent { constructor(private ngZone: NgZone) {} someFunction() { // 执行一些不涉及UI更新的操作 // 当需要更新UI时 this.ngZone.run(() => { // 更新ngModel绑定的变量 }); } }
- 确保
- 使用