What exactly $event object do in Angular 2?

匆匆过客 提交于 2019-12-17 07:25:10

问题


I am bit confused what exactly $event doing here and what is the difference between this two examples

<button (click)="clicked($event)"></button>

@Component(...)
class MyComponent {
  clicked(event) {
    event.preventDefault();
  }
}

and

<button (click)="clicked()">Click</button>



 @Component(...)
    class MyComponent {
      clicked(event) {
      }
    }

回答1:


$event is the event itself.

The event binding (someevent) allows to bind to DOM events and to EventEmitter events. The syntax is exactly the same.

For DOM events $event is the MouseEvent, KeyboardEvent, or the event value of the type of whatever event you listen to.

For EventEmitter events the emitted value is available as $event

Assuming this example $event refers to the emitted Ferrari car instance:

@Output() carChange:EventEmitter<Car> = new EventEmitter<Car>();

someMethod() {
  this.carChange.emit(new Car({name: 'Ferrari'}));
}

If you don't use $event like in (click)="clicked()" then the event value is not passed.

Actually as far as I remember it is still passed in some browsers but not in all (don't remember which ones)

But if you use Angulars WebWorker feature, then your method might not get the fired or emitted event if you don't explicitely list it.




回答2:


If you don't pass the $event in your template, then you won't have the $event variable in your clicked() method available.

See this Plunker for a quick comparison



来源:https://stackoverflow.com/questions/37944199/what-exactly-event-object-do-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!