2 回答

TA貢獻(xiàn)1895條經(jīng)驗 獲得超3個贊
如果您使用的是響應(yīng)式表單,則無需使用[selected]Nor (change),只需在創(chuàng)建表單時為 userName 賦予值即可
使用構(gòu)造函數(shù)
const firstId=usersModel[0].id
this.form=new FormGroup({
userName:new FormControl(firstId)
})
使用表單生成器
const firstId=usersModel[0].id
this.form=this.fb.group({
userName:firstId
})
創(chuàng)建表單后使用 setValue
const firstId=usersModel[0].id
this.form.get('userName').setValue(firstId)

TA貢獻(xiàn)1828條經(jīng)驗 獲得超4個贊
當(dāng)您使用 Angular 反應(yīng)形式時,請嘗試將邏輯保留在ts
文件本身中。
使用setValue(),您可以為控件設(shè)置默認(rèn)值。
要設(shè)置表單控件的默認(rèn)值,您可以這樣,
this.form.controls['country'].setValue(this.countries[0].id)
在模板中使用它,
<option?*ngFor="let?country?of?countries"?[value]="country.id"> ????{{?country.name?}} ????</option>
參考:
完整的示例代碼類似于,
應(yīng)用程序組件.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import {Country} from './country';
@Component({
? selector: 'my-app',
? templateUrl: './app.component.html',
? styleUrls: [ './app.component.css' ]
})
export class AppComponent? {
? countries = [
? ? {
? ? ? id: 'us',
? ? ? name: 'United States'
? ? },
? ? {
? ? ? id: 'uk',
? ? ? name: 'United Kingdom'
? ? },
? ? {
? ? ? id: 'ca',
? ? ? name: 'Canada'
? ? }
? ];
? form: FormGroup;
? ngOnInit(){
? ? ? this.form = new FormGroup({
? ? ? ? country: new FormControl('')
? ? ?});
? ? ?this.form.controls['country'].setValue(this.countries[0].id)
? }
}
應(yīng)用程序組件.html
<form [formGroup]="form">
? ? <select formControlName="country">
? ? ? ? <option *ngFor="let country of countries" [value]="country.id">
? ? ? ? ? ? {{ country.name }}
? ? ? ? </option>
? ? </select>
</form>
- 2 回答
- 0 關(guān)注
- 165 瀏覽
添加回答
舉報