2016-09-29 34 views
18

如何爲角度2反應形式中的所有表單字段設置默認值?Angular2反應形式 - 爲下拉式表單字段設置默認值

這裏是plnkr重現該問題

下面的代碼,因爲它有一個與之關聯的對象不更新下拉值。

注意:在這裏,我需要設置所有表單字段的默認值與從後端API接收到的響應。

Component.html

<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)"> 
    <div class="form-group"> 
     <label>Country:</label> 
     <select formControlName="country"> 
      <option *ngFor="let country of masterCountries" [ngValue]="country">{{country.countryName}}</option> 
     </select> 
    </div> 

    <div class="form-group"> 
     <label for="">Name</label> 
     <input type="text" class="form-control" formControlName="name"> 
     <small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)" class="text-danger"> 
      Name is required (minimum 5 characters). 
      </small> 
     <!--<pre class="margin-20">{{ myForm.controls.name.errors | json }}</pre>--> 
    </div> 
    <button type="submit" class="btn btn-default">Submit</button> 
    <div class="margin-20"> 
     <div>myForm details:-</div> 
     <pre>Is myForm valid?: <br>{{myForm.valid | json}}</pre> 
     <pre>Is myForm submitted?: <br>{{submitted | json}}</pre> 
     <pre>myForm value: <br>{{myForm.value | json}}</pre> 
    </div> 

Component.ts

export class AppComponent implements OnInit { 
    public myForm: FormGroup; 
    public masterCountries: any[] = [{"countryCode":"AF","countryName":"Afghanistan"},{"countryCode":"AL","countryName":"Albania"},{"countryCode":"DZ","countryName":"Algeria"},{"countryCode":"AS","countryName":"American Samoa"},{"countryCode":"AD","countryName":"Andorra"}]; 

    // Sample response received from backend api 
    public CountryResponse = {country: {"countryCode":"AF","countryName":"Afghanistan"}, name: 'test123'}; 
    constructor(private _fb: FormBuilder) { } 

    ngOnInit() { 

     // the short way 
     this.myForm = this._fb.group({ 
      country: [''], 
      name: ['', [<any>Validators.required, <any>Validators.minLength(5)]], 
     }); 


     (<FormGroup>this.myForm) 
      .setValue(this.CountryResponse, {onlySelf: true}); 


    } 


    save(model: User, isValid: boolean) { 
     this.submitted = true; 
     console.log(model, isValid); 
    } 
} 

讓我知道,如果有任何其他的方式來設置整個表單。

+0

的可能的複製[角2 - 綁定對象下拉並選擇基於事件的值](http://stackoverflow.com/questions/39105905/angular-2-bind-object-to-dropdown-and-select-value-based-on- an事件) –

+0

並且還有一個http://stackoverflow.com/questions/39745629/angular2-two-way-binding-to-select-option-not-u pdating –

+0

它不是重複的。我需要使用從後端收到的示例響應更新所有表單域。更新我的問題,以反映相同的 –

回答

5

只要改變這一點:

(<FormGroup>this.myForm) 
      .setValue(this.CountryResponse, {onlySelf: true}); 

分解爲:

const selectedCountry = this.masterCountries.find(country => country.countryCode === this.CountryResponse.country.countryCode) 
this.CountryResponse.country = selectedCountry; 
(<FormGroup>this.myForm) 
      .setValue(this.CountryResponse, {onlySelf: true}); 

正如說你需要在聲明的形式控制傳遞對象

7

您的代碼不起作用,因爲雖然你this.selectedCountry出現與this.masterCountries的要素之一具有相同的字段的值,他們不是同一個對象。這使得select.value === option.value的比較總是返回false

很簡單,使其作品,只是改變你的setValue功能如下:

(<FormControl>this.form.controls['country']) 
      .setValue(this.masterCountries[0], { onlySelf: true }); 

或創建FormGroup時,你可以將其設置:

this.myForm = this._fb.group({ 
     country: [this.masterCountries[0]], 
     name: ['', [<any>Validators.required, <any>Validators.minLength(5)]], 
    }); 
+1

感謝您的答案。是的,如果我使用masterCountries來設置值,它會工作。但我需要使用從後端收到的響應來設置整個表單。用這個場景更新我的plnkr。 https://plnkr.co/edit/GKguMzZbr0kzrraPP73f?p=preview –

0

的確切相同的參考或初始化之前經過的默認值作爲參數

MyFormControl: FormControl = new FormControl('Default value');