Pages

How to create Cascading Drop Down (Country and State list) In Angular 6

              How to make dependent another dropdown for filter in angular

To build a cascading dropdown, we have to take two dropdown.

Add the following code in html file.

<select [(ngModel)]="country" (change)="setState()">
    <option value="India">India</option>
    <option value="Australia">Australia</option>
</select>


<select>
    <option *ngFor="let state of states" value="state">{{state}}</option>
</select>

The second dropdown option will be fetched dynamically. So, here we will use the concept of (ngFor) loop which can be used to populate an html template based on the condition. 

Suppose, if there are 3 state then option will be repeated 3 times and will be stored into select element.

We need to define the array (states) in our ts file. It will take count of the state and on based on the count it push the value in the state and it will repeat n number of times.

On every value change in the option, the value will be stored in two way binding [(ngModel)] and the change function will be triggered. We declare the function in ts file.

Now, place the following code in ts file.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit{
  ngOnInit() {}
  states = ["string"]
  country!: string;

  setState() {
    if(this.country == "India")
    {
      this.states = ["Bihar","Uttar Pradesh","Uttrakhand","Goa","Rajasthan"];
    }
    if(this.country == "Australia")
    {
      this.states = ["New South Wales","Victoria","Queensland","Western Australia",
"South Australia"];
    }
  }
}


The output for this will be :






No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...