PGH
PGH

Reputation: 2204

2-way data binding in select component using of the reactive form

I am using select component to display some countries and their associated states and languages like this:

enter image description here

Here i need to perform 2-way data binding, I want to change states and languages dropdown list according to the selection made in Country.

I know this is the duplicate of this QUESTION, Here they are using template driven forms, but i want to perform it for reactive forms.

Stackcblitz DEMO

Upvotes: 0

Views: 376

Answers (1)

Nick Wang
Nick Wang

Reputation: 624

try it:

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

export interface Country {
  value: string;
  viewValue: string;
}
export interface State {
  country: string;
  value: string;
  viewValue: string;
}
export interface Language {
  state: string;
  value: string;
  viewValue: string;
}
/**
 * @title Basic select
 */
@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
  public selCountry;
  public selState;
  countries: Country[] = [
    {value: 'IND', viewValue: 'India'},
    {value: 'AUS', viewValue: 'Austarlia'},
    {value: 'ENG', viewValue: 'England'}
  ];

   states: State[] = [
    {country: 'IND', value: 'KAR', viewValue: 'Karnataka'},
    {country: 'IND', value: 'TEL', viewValue: 'Telangana'},
    {country: 'AUS', value: 'KL', viewValue: 'Kerala'}
  ];
    languages: Language[] = [
    {state: 'KL', value: 'KN', viewValue: 'Kannada'},
    {state: 'KAR', value: 'TL', viewValue: 'Telugu'},
    {state: 'TEL', value: 'ML', viewValue: 'Malayalam'}
  ];
  getStates() {
    return this.states.filter(item => {
return item.country == this.selCountry;
    });
  }
  getLanguages() {
    return this.languages.filter(item => {
return item.state == this.selState;
    });
  }
}


<mat-form-field>
  <mat-select placeholder="Country" [(ngModel)]="selCountry">
    <mat-option *ngFor="let country of countries" [value]="country.value">
      {{country.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
  <mat-select placeholder="States" [(ngModel)]="selState">
    <mat-option *ngFor="let state of getStates()" [value]="state.value">
      {{state.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
  <mat-select placeholder="Language">
    <mat-option *ngFor="let language of getLanguages()" [value]="language.value">
      {{language.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

Upvotes: 1

Related Questions