Angular 中的 @Input 和 @Output 装饰器是用于组件间通信的重要机制

这些装饰器帮助我们将数据从父组件传递到子组件(@Input),以及将事件从子组件传递到父组件(@Output)

 

@Input

@Input 装饰器用于定义一个输入属性,这样我们就可以从父组件绑定数据到子组件。当父组件的属性变化时,这些变化也会自动传递到子组件

在这个例子中,parentMessage 是父组件中的一个属性,当它变化时,子组件中的 message 属性也会相应更新

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: '<p>{{ message }}</p>',
})
export class ChildComponent {
  @Input() message: string;
}
<app-child [message]="parentMessage"></app-child>

@Output

@Output 装饰器用于定义一个输出属性,这通常是一个事件发射器(EventEmitter)。当子组件中发生某些事情时,它可以触发事件,并将数据发送回父组件

在这个例子中,当子组件中的按钮被点击时,notify 方法会被调用,进而触发 notifyEvent 事件,并将消息传递给父组件

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: '<button (click)="notify()">Notify Parent</button>',
})
export class ChildComponent {
  @Output() notifyEvent = new EventEmitter<string>();

  notify() {
    this.notifyEvent.emit('Something happened!');
  }
}
<app-child (notifyEvent)="handleNotification($event)"></app-child>

 

通过这种方式,@Input 和 @Output 装饰器提供了组件之间清晰的、基于契约的通信方式,有助于保持组件的独立性和可重用性