Reputation: 501
I'm new to Angular and front end stuff in general, and I'm trying to understand and implement a way to make changes based on actions from a user. For example, I have a drop down form in my view and when a user selects or inputs something I want to trigger something to happen in my component like make a http request to fill a table on the view but I just don't really understand how to do something like that. On a button it makes sense, you have the button execute a function on click but other than that I'm lost... Any help would be greatly appreciated.
Upvotes: 1
Views: 1821
Reputation: 587
Another approach is to use Angular's Reactive forms. It has a little more set up but is useful if you intend to use it in a form since it comes with some more features.
You can use the FormBuilder
helper to create a FormGroup
. Once you have your form object, you can attach a listener to the form control to detect changes.
// attch listener to form changes
this.form.get("<your_form_control>").valueChanges.subscribe(value => {
// do stuff like call your API
})
This code attaches the listener to a particular form control, but you can also attach it to the form if you want to capture anytime any value gets changed on the form.
I created a sample app for reference using the form control listener approach: https://stackblitz.com/edit/angular-ivy-6aqbce?file=src/app/app.component.ts
Upvotes: 0
Reputation: 1166
You can do this buy using onChange DOM event. Simply bind your handler function with change event of you dropdown like below.
Demo.html
<select class="form-control" name="country" (change)="countryDropDownChangeHandler($event)">
<option value="IN">India</option>
<option value="US">United States of America</option>
</select>
Demo.component
countryDropDownChangeHandler(event) {
// Perform api stuff
}
Upvotes: 2