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

前端 未结 7 1673
不知归路
不知归路 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:33

    You can use the patch function for setting defaults with some of the values in your form group.

    component.html

    component.ts

    import { FormControl, FormGroup, Validators } from '@angular/forms';
    
    export class Component implements OnInit{
    
        countries: string[] = ['USA', 'UK', 'Canada'];
        default: string = 'UK';
    
        countryForm: FormGroup;
    
        constructor() {
    
            this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
        }
    }
    
    ngOnInit() {
        this.countryForm = new FormGroup({
          'country': new FormControl(null)
        }); 
    
        this.countryForm.patchValue({
          'country': default
        });
    
      }
    

提交回复
热议问题