Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

typescript - What exactly $event object do in Angular 2?

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) {
      }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...