英文:
How can I Take value of input field and put in Form Builder?
问题
HTML:
<input class="form-control" formControlName="rolaId" type="text" value="2" placeholder="Prosumer">
.ts:
this.signUpForm = this.forma.group({
name: ['', Validators.required],
rolaId: ['2', Validators.required],
})
在这段代码中,HTML 中的 value
属性已经被设置为 "2",而在 TypeScript 文件中,rolaId
表单控件的默认值也被设置为 "2"。这应该确保 Form Builder 中的 rolaId
的默认值为 2。
英文:
I have input field which value must be 2, but in that field must be written "Prosummer" and then I need to put value of 2 in Form Builder.I am using Angular 15.This is my code:
HTML:
<input class="form-control" formControlName="rolaId" type="text" value="2" placeholder="Prosumer">
.ts
this.signUpForm = this.forma.group({
name: ['', Validators.required],
rolaId:['', Validators.required],
})
When I run this code placeholder is Prosumer but in Form Builder value of rolaId is not 2.
答案1
得分: 2
Since you are using ReactiveFormsModule
, you have control over your form in your code, not in the template HTML, so setting the value of 2 with [value]="2"
is not going to work.
If you want to set up that hard-coded value initially, you could do it when the form is created, providing an initial value:
rolId = 2;
createForm(): void {
this.signUpForm = this.forma.group({
name: ['', Validators.required],
rolaId: [this.rolId, Validators.required],
})
}
Or maybe you are getting that value from somewhere else, sometime later, you could then patch
the particular form property rolaId
using patchValue
:
updateRolId(id: number): void {
this.form.get('rolaId')?.patchValue(id);
}
For more information about reactive forms, I suggest reading the official docs.
英文:
Since you are using ReactiveFormsModule
, you have control over your form in your code, not the in the template HTML, so setting the value of 2 with [value]="2"
is not going to work.
If you want to set up that hard-coded value initially, you could do it when the form is created, providing an initial value
rolId = 2;
createForm(): void {
this.signUpForm = this.forma.group({
name: ['', Validators.required],
rolaId:[this.rolId, Validators.required],
})
}
Or maybe you are getting that value from somewhere else, sometime later, you could then patch
the particular form property rolaId
using patchValue
:
updateRolId(id: number): void {
this.form.get('rolaId')?.patchValue(id);
}
For more information about reactive forms, I suggest reading the official docs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论