How To Use Dropdown In Angular

How To Use Dropdown In Angular

When there are several options to pick from, we employ choose options. In this Angular article, we will learn how to use them. We will show you how to change the select's Default Value. Listen for and react to the Select option change event. Update the Dropdown list option dynamically and set the value dynamically, for example. Both Reactive Forms and Template-driven Forms will be covered.

Select Options in Reactive Forms

As seen below, use the Reactive Form to create a contactForm. The country field is the only formControl field on the form. The nations array will provide the value for the country. The ID will be saved in the nation field.

export class AppComponent implements OnInit  { 
 
  contactForm:FormGroup;
 
  countries = [
    { id: 1, name: "United States" },
    { id: 2, name: "Australia" },
    { id: 3, name: "Canada" },
    { id: 4, name: "Brazil" },
    { id: 5, name: "England" }
  ];
 
  constructor(private fb:FormBuilder) {
  }
 
  ngOnInit() {
 
    this.contactForm = this.fb.group({
      country: [null]
    });
  }
 
  submit() {
    console.log("Form Submitted")
    console.log(this.contactForm.value)
  }
 
}

The country selection option is as shown below.
<form [formGroup]="contactForm" (ngSubmit)="submit()">
 
<p>
 
  <select formControlName="country">
    <option [ngValue]="null" disabled>Select Country</option>
    <option *ngFor="let country of countries" [ngValue]="country.id">{{country.name}}</option>
  </select>
 
  <button type="submit">Submit</button>
</p>
 
</form>

The formControlName directive associates the select with the contactForm nation field. (<select formControlName="country">)

<option [ngValue]="null" disabled > disabled When no values is specified or when country is null, the Select Country option appears.

The ngFor runs through the "countries" array, displaying the country.name in the drop-down menu. The country can also be displayed. name - country.id or any other country object.

We'd like to have the country's ID back. As a result, we employ the [ngValue]="country.id" attribute. You can also use [ngValue]="country," in which case the country object will be returned.


How To Add Select Option Dropdown In Reactive Forms

Set the Default Value for the select

We can use either setValue or patchValue to change the value of a FormControl.

To pass the default value, set the default values while defining the form. The following code makes Australia the default country. When we load the component for the first time, this only works once.
ngOnInit() {
    this.contactForm = this.fb.group({
      country: [2]
    });
)

The other option is to construct a stand-alone setDefaults method that you may use at any time.
ngOnInit() {
 
  this.contactForm = this.fb.group({
    country: [null]
  });
 
  this.setDefaults();
}
 
setDefaults() {
  this.contactForm.get("country").patchValue(null);
}

Listen to the Select option change event

The valueChanges event is used to listen to the change event, as seen below.
this.contactForm.get("country").valueChanges
  .subscribe(f=> {
    this.onCountryChanged(f);
})

onCountryChanged(value) {
  console.log('onCountryChanged')
  console.log(value)
}

Dynamically update the Drop down option

You can dynamically add or remove countries from the array, and the changes will be reflected in the drop down menu right away.

Inquire about adding a new country to the template.
//Template
 
<p>
  <input [(ngModel)]="country_name">
  <button (click)="addCountry()">Add</button>
</p>

After ensuring it does not exist, add it to the nations array.
//Component
 
 country_name="";
 
 addCountry() {
    const country = this.countries.find(el => el.name === this.country_name);
    if (!country) {
      let id=Math.max.apply(Math, this.countries.map(function(o) { return o.id; }))
      this.countries.push({id:id+1, name:this.country_name})
      this.country_name="";
    }
  }

Dynamically Set Value

The following code changes the country's value dynamically.
//Template
 
<p>
  <input [(ngModel)]="set_country">
  <button (click)="setCountry()">Set Country</button>
</p>

//Component
 
set_country="";
 
setCountry() {
  const country = this.countries.find(el => el.name === this.set_country);
  if (country) {
    this.contactForm.get("country").patchValue(country.id);
  }
}

The following code is the complete code of the app.component.html
<h1> Angular Select Option Example</h1>
 
<form [formGroup]="contactForm" (ngSubmit)="submit()">
 
<p>
 
  <select formControlName="country">
    <option [ngValue]="null" disabled>Select Country</option>
    <option *ngFor="let country of countries" [ngValue]="country.id">{{country.name}}</option>
  </select>
 
  <button type="submit">Submit</button>
</p>
 
</form>
 
<p>
  <input [(ngModel)]="country_name">
  <button (click)="addCountry()">Add</button>
</p>
 
 
<p>
  <input [(ngModel)]="set_country">
  <button (click)="setCountry()">Set Country</button>
</p>

The following code is the complete code of the app.component.ts
import { Component, ViewChild, OnInit } from '@angular/core';
import { NgForm, FormGroup, FormControl, FormBuilder } from '@angular/forms';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 
  title = 'Angular Select Options Example';
  contactForm: FormGroup;
 
  constructor(private fb: FormBuilder) {
  }
 
  country_name="";
  set_country="";
 
  countries = [
    { id: 1, name: "United States" },
    { id: 2, name: "Australia" },
    { id: 3, name: "Canada" },
    { id: 4, name: "Brazil" },
    { id: 5, name: "England" }
  ];
 
 
  ngOnInit() {
 
    this.contactForm = this.fb.group({
      country: [null]
    });
 
    this.setDefaults();
 
    this.contactForm.get("country").valueChanges
      .subscribe(f => {
        this.onCountryChanged(f);
      })
  }
 
  submit() {
    console.log("Form Submitted")
    console.log(this.contactForm.value)
  }
 
  setDefaults() {
    this.contactForm.get("country").patchValue(null);
  }
 
  onCountryChanged(value) {
    console.log('onCountryChanged')
    console.log(value)
  }
 
  addCountry() {
    const country = this.countries.find(el => el.name === this.country_name);
    if (!country) {
      let id=Math.max.apply(Math, this.countries.map(function(o) { return o.id; }))
      this.countries.push({id:id+1, name:this.country_name})
      this.country_name="";
    }
  }
 
  setCountry() {
    const country = this.countries.find(el => el.name === this.set_country);
    if (country) {
      this.contactForm.get("country").patchValue(country.id);
    }
  }
}

Now, run the application and see the output looks like below

Example of Dropdown In Reactive form


Select Options in Template Driven Forms

The choose choices in Template Driven Forms are coded as follows. Refer to the article on how to set values in template-driven forms for further information.

Using the @ViewChild, we acquire the reference to the contactForm.

Wait for a change detection cycle with setTimeout() so that the @ViewChild updates the reference to the contactForm. The contactForm will return null without it.

We use the (ngModelChange)="onCountryChanged($event)" event binding to listen to the change. We can also make use of the valueChanges property.

The rest of the code is almost identical to the Reactive forms.

The following code is the complete code of the app.component.ts
import { Component, ViewChild, OnInit } from '@angular/core';
import { NgForm, FormGroup, FormControl, FormBuilder } from '@angular/forms';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
 
  title = 'Angular Select Options Example';
  
  @ViewChild("contactForm",null) contactForm:NgForm;
 
 
  constructor(private fb: FormBuilder) {
  }
 
  country_name="";
  set_country="";
 
  countries = [
    { id: 1, name: "United States" },
    { id: 2, name: "Australia" },
    { id: 3, name: "Canada" },
    { id: 4, name: "Brazil" },
    { id: 5, name: "England" }
  ];
 
 
  ngOnInit() {
 
    setTimeout(() => { 
      this.setDefaults();
 
    })
 
  }
 
  submit() {
    console.log("Form Submitted")
    console.log(this.contactForm.value)
  }
 
  setDefaults() {
    this.contactForm.form.get("country").patchValue(null);
  }
 
  onCountryChanged(value) {
    console.log('onCountryChanged')
    console.log(value)
  }
 
 
  addCountry() {
    const country = this.countries.find(el => el.name === this.country_name);
    if (!country) {
      let id=Math.max.apply(Math, this.countries.map(function(o) { return o.id; }))
      this.countries.push({id:id+1, name:this.country_name})
      this.country_name="";
    }
  }
 
  setCountry() {
    const country = this.countries.find(el => el.name === this.set_country);
    if (country) {
      this.contactForm.form.get("country").patchValue(country.id);
    }
  }
 
}

The following code is the complete code of the app.component.html
<h1> Angular Select Option Example</h1>
 
<form #contactForm="ngForm" (ngSubmit)="submit()">
 
  <p>
  
    <select name="country" ngModel (ngModelChange)="onCountryChanged($event)">
      <option [ngValue]="null" disabled>Select Country</option>
      <option *ngFor="let country of countries" [ngValue]="country.id">{{country.name}}</option>
    </select>
  
    <button type="submit">Submit</button>
  
  </p>
  
  </form>
 
<p>
  <input [(ngModel)]="country_name">
  <button (click)="addCountry()">Add</button>
</p>
 
 
<p>
  <input [(ngModel)]="set_country">
  <button (click)="setCountry()">Set Country</button>
</p>

Conclusion

In this article, we learned how to add Dropdown option in Angular Reactive form and template driven forms. We covered how to change the select's Default Value. Listen for and react to the Select option change event.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post