Event Binding in Angular 2 (v11)
Events are handled in Angular using the following special syntax.
(target event name) = "template statement"
Bind the target event name within parentheses on the left of an equal sign, and event handler method or statement on the right.
<button (click)="onShow()">Show</button>
Above, (click)
binds the button click event and onShow()
statement calls the onShow()
method of a component.
@Component({
selector: 'event-demo,
template: '<button (click)="onShow()" >Show</button>'
})
export class EventBindingDemoComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
onShow() {
alert('Show button clicked!');
}
}
Alternatively, use the on- prefix, known as the canonical form:
<button on-click="onShow()" >Show</button>
By default, an event propagates up to the parent container event. In the following example, click event propagates to click of div and will call both the onShow()
and onDivClick()
methods.
<div (click)="onDivClick()">
<button (click)="onShow()" >Show</button>
</div>
$event
Mostly, when an event is raised, you may need to pass some value to the event handler function. This value can be number, string, or an object that contains information about an event.
You can pass the number or string value to the event handler function, as shown below.
<button (click)="onShow(20)">Show</button>
Angular includes $event
that contains the information about an event. The type of $event depends on the target event, e.g., if the target event is a native DOM element event, then it is an object.
<button (click)="onShow($event)">Show</button>
A component should define the onShow(event)
method where the type of the parameter can be KeyboardEvent, MouseEvent, etc. If you don't know the exact event type, they use “any” type, as shown below.
onShow(event:any) {
console.log(event);
}
If event is a native DOM element event then $event.target
get DOM element reference using which you can access element's property e.g. $event.target.innerHTML
returns the value of innerHTML property of a DOM element.
<button (click)="onShow($event)">Show</button>
//component method
onShow(event:any) {
alert(event.target.innerHTML); // returns Show
}
You can use $event.target
in the template statement. The following example binds a component property to $event.target.value
of the input box on the input event without using ngModel
.
<input type="text" (input)="userName=$event.target.value"><br/>
{{userName}}
Learn more about event binding.