Search code examples
angulardropdown

Set a default value for Angular chain dropdown


I had JSON country within ID, and what I want to is the defeulat value is set to selected, here my select code so far:

<select (change)="onNationalitySelected($event.target.value)" id="nationality" formControlName="nationality">
                <option value=""> {{'messages.dropdownselect' | translate}} </option>
                <option *ngFor="let country of countries" [value]="country.id" [selected]="country.id == '100'" >
                  {{ country.name }}
                </option>
              </select>

.ts file

  onNationalitySelected(nationalityId: number) {
    this.customer.coid = nationalityId;
    this.customer.nationality = this.countries.filter(
      c => (c.id == nationalityId)
    )[0].name;

I tried to set a default value for country is 100, but it's not working, the value still empty after saved to DB.

Thanks for any comments.


Solution

  • ts

    // Let's use FormGroup so we can add a control/default
    countryForm: FormGroup;
    
    // define our countries data
    countries = [{
     id: '100',
     name: 'USA',
     code: 'USD'
    },
    {
     id: '200',
     name: 'Canada',
     code: 'CAD'
    },
    {
     id: '300',
     name: 'UK',
     code: 'GBP'
    }];
    
    constructor(private fb: FormBuilder) {}
    
    ngOnInit() {
     // set country code 100 as default
     this.countryForm = this.fb.group({
      countryControl: [this.countries[0].id]
     });
    }
    

    html

    // ngValue allows us to use an object for default value assignment
    <option [ngValue]="country.id" *ngFor="let country of countries">{{country.name}}</option>
    

    I'm a little uncertain about countryControl: [this.countries[0].id], if it doesn't work, try this instead: countryControl: [this.countries[0]]

    Let me know how it goes!