Angular 4 - Select default value in dropdown [Reactive Forms]

前端 未结 7 1641
不知归路
不知归路 2020-12-01 00:52

In Angular 4, I have the following configuration defined in a json config file.

 countries: [\'USA\', \'UK\', \'Canada\'];
 default: \'UK\'

相关标签:
7条回答
  • 2020-12-01 01:41

    Try like this :

    component.html

    <form [formGroup]="countryForm">
        <select id="country" formControlName="country">
            <option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
        </select>
    </form>
    

    component.ts

    import { FormControl, FormGroup, Validators } from '@angular/forms';
    
    export class Component {
    
        countries: string[] = ['USA', 'UK', 'Canada'];
        default: string = 'UK';
    
        countryForm: FormGroup;
    
        constructor() {
            this.countryForm = new FormGroup({
                country: new FormControl(null);
            });
            this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
        }
    }
    
    0 讨论(0)
提交回复
热议问题