MST

星途 面试题库

面试题:Angular事件绑定中如何实现自定义事件与双向绑定优化

假设你正在开发一个自定义的表单组件,需要实现一个自定义的提交事件。请阐述如何在Angular中定义并触发这个自定义事件,同时在父组件中进行监听处理。另外,对于该表单组件中使用到的双向绑定,如ngModel,如何进行性能优化,避免不必要的变更检测。
22.1万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

定义并触发自定义提交事件

  1. 在子组件中定义事件
    • 在子组件的 .ts 文件中,从 @angular/core 导入 EventEmitterOutput
    • 声明一个 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();
      }
    }
    
  2. 在子组件模板中触发事件
    • 在表单的提交按钮或提交逻辑处调用触发函数。例如:
    <form (ngSubmit)="onSubmit()">
      <!-- 表单内容 -->
      <button type="submit">提交</button>
    </form>
    
  3. 在父组件中监听处理
    • 在父组件的模板中使用子组件,并监听自定义事件。例如:
    <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('自定义提交事件被触发');
        // 处理提交后的逻辑
      }
    }
    

双向绑定及性能优化

  1. ngModel性能优化
    • 使用 ChangeDetectionStrategy.OnPush
      • 在子组件的 @Component 装饰器中设置 changeDetectionChangeDetectionStrategy.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绑定的变量
          });
        }
      }