Select dependent on angular 2

1

I am trying to make a select dependent on countries that, when selecting a country, load the states but I can not find a way to do it in Angular 2

      <div class="col-md-4">
                    <div class="form-group">
                      <label for="pais"> {{'etq.pais' | i18n}}</label>
                      <select id="pais" [(ngModel)]="lugar.idPais" name="idPais" class="form-control">
                        <option value="" disabled><{{'etq.seleccione' | i18n}}></option>
                        <option *ngFor="let pais of paisesArray" [value]="pais.id" >{{pais.descripcion}}</option>
                      </select>

                    </div>
                  </div>
    
asked by Gonzalo Alberto 26.07.2017 в 17:32
source

2 answers

0

You have to set two lists in your component.ts , one for the countries eg: let paises: Pais[] and one for the states let estados: Estado[]

Then you set to each select that the dataprovider will be the newly created EJ;

<select [(ngModel)]="paises">
   <option [ngValue]="pais" *ngFor="let pais of paises" (click)="handleChange(item)">{{label(item)}}</option>
</select>

Y

<select [(ngModel)]="estados">
  <option [ngValue]="estado" *ngFor="let estado of estados" (click)="handleChange(item)">{{label(item)}}</option>
</select>

Finally in the handleChange method you change the list of states according to the country passed by parameter, something like:

handleChange(pais) {
   this.estados = pais.estados;
}
    
answered by 09.08.2017 в 21:19
0

You can use ngModelChange to detect changes in the state of your model.

<select [(ngModel)]="lugar.idPais" (ngModelChange)="handlePaisChange($event.target.data)">
  <option value="" disabled><{{'etq.seleccione' | i18n}}></option>
  <option *ngFor="let pais of paisesArray" [value]="pais.id" >{{pais.descripcion}</option>
</select>

handlePaisChange(pais) {
  this.estados = // código para obtener estados con pais;
}

Source: link

    
answered by 15.11.2018 в 08:43