我嘗試了以下方法,但輸入欄位為空白。
<div class="form-group">
<label>First name:</label>
<input type="text" class="form-control" placeholder="John" formControlName="firstname" value="{{this.session_user[0].firstName}}">
</div>
uj5u.com熱心網友回復:
據我了解,您想將默認值設定為 FormControl 值,我想您的代碼是這樣的
constructor(private fb: FormBuilder) { }
public form: FormGroup = this.fb.group({
firstname: ['This is the default value', // Default value
[
Validators.required // Validators here if needed
]
]
});
使用FormBuilder設定一個默認值,可以像上面的例子一樣,當然也可以是變數。
如果您在定義 FormGroup 時還沒有該值,則可以隨時設定該值
this.form.setValue({ firstname: "New value" });
請注意,如果您的輸入元素不在表單元素中,則上面的代碼將不起作用,如下例所示
<form class="form-group" [formGroup]="form">
<label>First name:</label>
<input type="text" class="form-control" placeholder="John" formControlName="firstname">
</form>
無需為輸入元素設定值屬性。
如果您不想使用 FormControl,那么您可以使用 ngModel
<input type="text" placeholder="John" [(ngModel)]="session_user[0].firstName">
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/475267.html
上一篇:如何修復下拉按鈕(HTML)
