取输入字段的值并放入表单生成器中。

huangapple go评论72阅读模式
英文:

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:

&lt;input class=&quot;form-control&quot; formControlName=&quot;rolaId&quot; type=&quot;text&quot; value=&quot;2&quot; placeholder=&quot;Prosumer&quot;&gt;

.ts

  this.signUpForm = this.forma.group({
  name: [&#39;&#39;, Validators.required],
  rolaId:[&#39;&#39;, 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]=&quot;2&quot; 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: [&#39;&#39;, 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(&#39;rolaId&#39;)?.patchValue(id);
}

For more information about reactive forms, I suggest reading the official docs

huangapple
  • 本文由 发表于 2023年5月14日 12:51:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定