1

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.

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.