📜  向子组件 angular 发送事件 - Javascript (1)

📅  最后修改于: 2023-12-03 15:22:58.396000             🧑  作者: Mango

向子组件 Angular 发送事件 - Javascript

Angular 是一个流行的前端框架,它提供了一种简单的方式来向子组件发送事件。下面将介绍如何在 Angular 中发送事件给子组件。

发送事件

要向子组件发送事件,需要使用 EventEmitter 对象。这个对象是在 @angular/core 库中定义的。这里有一个示例:

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

@Component({
  selector: 'app-parent',
  template: `
    <button (click)="increment()">Increment</button>
    <app-child [count]="count" (countChanged)="onCountChanged($event)"></app-child>
  `,
})
export class ParentComponent {
  count = 0;
  @Output() countChanged = new EventEmitter<number>();

  increment() {
    this.count++;
    this.countChanged.emit(this.count);
  }

  onCountChanged(count: number) {
    this.count = count;
  }
}

在这个例子中,我们创建了一个父组件 ParentComponent 和一个子组件 ChildComponent。当父组件中按钮被点击时,通过 EventEmitter 对象将计数器的值传递给子组件。子组件也定义了一个 @Output 事件,可以用来将其自身的变化传递回父组件。

子组件接收事件

子组件中需要使用 @Input 装饰器来接收来自父组件的数据。这里有一个示例:

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

@Component({
  selector: 'app-child',
  template: `
    <p>{{ count }}</p>
  `,
})
export class ChildComponent {
  @Input() count = 0;
}

在这个例子中,子组件使用了 @Input 装饰器来接收来自父组件的计数器值。当父组件中的计数器值发生变化时,子组件会立即更新其自身的计数器值。

总结

向子组件发送事件之间的核心是创建一个 EventEmitter 对象和 @Output 装饰器。父组件使用 EventEmitter 对象发出事件,子组件使用 @Input 装饰器接收事件。这种方式很方便,可以帮助开发人员更好地组织代码,提高代码的可读性和可维护性。

以上就是在 Angular 中向子组件发送事件的介绍。希望对您有所帮助!