是否可以将表达式传递给输入标签的值属性?
Is it possible to pass an expression to the value attribute of an input tag?
我尝试了以下方法,但输入字段是空白的。
<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>
据我了解,您想将默认值设置为 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">
我尝试了以下方法,但输入字段是空白的。
<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>
据我了解,您想将默认值设置为 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">