MST
星途 面试题库

面试题:Angular属性绑定与事件绑定的复杂场景处理

假设你有一个包含多个子组件的Angular应用,每个子组件都有一些可交互的元素。要求通过属性绑定实现一个全局的配置参数,影响所有子组件的显示样式;同时,通过事件绑定实现当任何一个子组件的特定按钮被点击时,更新全局的一个状态变量,并反映在所有相关子组件上。请描述实现思路以及关键代码片段。
38.3万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 属性绑定实现全局配置参数影响子组件样式
    • 在父组件中定义一个全局配置对象,包含影响子组件显示样式的参数。
    • 通过 @Input() 装饰器将配置对象传递给子组件,子组件根据接收到的配置参数动态设置自身的样式。
  2. 事件绑定实现子组件按钮点击更新全局状态变量
    • 在父组件中定义一个全局状态变量。
    • 子组件通过 @Output() 装饰器和 EventEmitter 来发射事件,当特定按钮被点击时,向父组件发射事件。
    • 父组件监听子组件发射的事件,接收到事件后更新全局状态变量,然后通过属性绑定将更新后的状态变量传递给所有相关子组件,子组件根据新的状态变量更新自身显示。

关键代码片段

  1. 父组件(app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  globalConfig = {
    styleParam: 'default - style'
  };
  globalStatus = 0;

  handleChildClick() {
    this.globalStatus++;
  }
}
<!-- app.component.html -->
<app - child - component
  [config]="globalConfig"
  (childClick)="handleChildClick()"></app - child - component>
<app - another - child - component
  [config]="globalConfig"
  (childClick)="handleChildClick()"></app - another - child - component>
  1. 子组件(child - component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app - child - component',
  templateUrl: './child - component.html',
  styleUrls: ['./child - component.css']
})
export class ChildComponent {
  @Input() config: any;
  @Output() childClick = new EventEmitter<void>();

  onButtonClick() {
    this.childClick.emit();
  }
}
<!-- child - component.html -->
<button (click)="onButtonClick()">Click me</button>
<div [ngStyle]="{ 'background - color': config.styleParam }">
  This is a child component
</div>
  1. 另一个子组件(another - child - component.ts 类似)
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app - another - child - component',
  templateUrl: './another - child - component.html',
  styleUrls: ['./another - child - component.css']
})
export class AnotherChildComponent {
  @Input() config: any;
  @Output() childClick = new EventEmitter<void>();

  onButtonClick() {
    this.childClick.emit();
  }
}
<!-- another - child - component.html -->
<button (click)="onButtonClick()">Click me</button>
<div [ngStyle]="{ 'color': config.styleParam }">
  This is another child component
</div>