简体   繁体   English

如何在 angular 中创建和触发自定义事件

[英]How to create and fire a custom event in angular

I'm new in Angular and I've read about event binding so I can do something like this:我是 Angular 的新手,我已经阅读了有关事件绑定的信息,因此我可以执行以下操作:

<button (click)="doSomething()"></button>

I'd like to know if it's possible to create a custom event and do the same thing.我想知道是否可以创建自定义事件并做同样的事情。 Let's say that I want to have a custom event like: deleteItem , is it possible to do something like this?假设我想要一个自定义事件,例如: deleteItem ,是否可以做这样的事情? And how?如何?

<my-component (deleteItem)="doSomething()"></my-component>

Of course, you can use an eventEmitter in my-component ts file add this当然,你可以在 my-component ts 文件中使用eventEmitter添加这个

 @Output() deleteItem= new EventEmitter();

and when you want to rise the event do this当你想提升事件时,请执行此操作

  this.deleteItem.emit();

also you can pass data like this你也可以像这样传递数据

  this.countUpdate.emit({value: some data });

then catch it in the parent component like this然后像这样在父组件中捕获它

<my-component (deleteItem)="doSomething($event)"></my-component>

and in the parent ts file并在父 ts 文件中

    doSomething(event)
    { 
       console.log(event);
    }

You should check out Angular's documentations example for parent listens to child event :您应该查看 Angular 的文档示例,了解父监听子事件

You declare a class property with the @Output() decorator and instantiate it to a new EventEmitter instance.您使用@Output()装饰器声明一个类属性并将其实例化为一个新的 EventEmitter 实例。

Example from the Angular docs来自Angular 文档的示例

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

@Component({
  selector: 'app-voter',
  template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)"  [disabled]="didVote">Agree</button>
    <button (click)="vote(false)" [disabled]="didVote">Disagree</button>
  `
})
export class VoterComponent {
  @Input()  name: string;
  @Output() voted = new EventEmitter<boolean>();
  didVote = false;

  vote(agreed: boolean) {
    this.voted.emit(agreed);
    this.didVote = true;
  }
}

Remember it is good practice to always add generic typing to the EventEmitter if it emits a value.请记住,如果 EventEmitter 发出值,则始终为其添加通用类型是一种很好的做法。

If an event emits a boolean value you should instantiate it with @Output() eventName = new EventEmitter<boolean>();如果一个事件发出一个布尔值,你应该用@Output() eventName = new EventEmitter<boolean>();实例化它@Output() eventName = new EventEmitter<boolean>();

The component above could be used in a parent component with <app-voter (voted)="handleVote($event)"></app-voter>上面的组件可以在带有<app-voter (voted)="handleVote($event)"></app-voter>的父组件中使用

EventEmitter 可以用来创建你自己的自定义事件,eventemitter 是 angular 框架中的对象。

@Output() deleteItem= new EventEmitter<{itemName:string}>(); ItemName=''; this.deleteItem.emit({ItemName=this.itemName});

@Output() loaderStatus= new EventEmitter<{Status:boolean}>(); Status=true; 
this.loaderEvent.emit({Status=false});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM