【问题标题】:Assign the value of a checkbox to a FormControlName (Angular)将复选框的值分配给 FormControlName (Angular)
【发布时间】:2021-09-27 22:56:03
【问题描述】:

我有一个响应式表单,想要获取复选框的值(不是“true”或“false”)并将其分配给 formControlName (selectedSizeValueControl)。

我尝试了一些方法,但它们对我不起作用。

有人可以帮忙吗?

代码:


    <form [formGroup]="variantForm" (ngSubmit) = "submit()">
    
      <mat-checkbox value="{{selectedSizeValue}}" formControlName = "selectedSizeValueControl"  >{{selectedSizeValue}}</mat-checkbox>
     
      <mat-radio-button value="{{sale_preis.value}}"><input type="text" #sale_preis formControlName ="sale_preis"></mat-radio-button>
    
      <button >save</button>
    </form>

组件.ts

selectedSizeValues: string;

variantForm = new FormGroup({
    selectedSizeValueControl: new FormControl(),
    sale_preis: new FormControl()  });

submit(){
    console.log(this.variantForm.value);

  }

selectedSizeValueControl 只取 TRUE 或 FALSE,我希望它取 selectedSizeValue 的值(例如:一个字符串)

谢谢大家!

【问题讨论】:

  • 能分享一下你的component.ts代码吗?
  • 嗨@DevangPatel:我已经添加了component.ts。
  • selectedSizeValue 是什么?复选框只能选中或取消选中,您要在selectedSizeValueControl 中存储什么样的值?

标签: angular checkbox angular-reactive-forms formgroups


【解决方案1】:

mat-checkbox 只能处理真假,不会取字符串。将元素更改为 input 或将 selectedSizeValues 的类型更改为布尔值。

【讨论】:

    【解决方案2】:

    我已经成功了。

    • 不要将 formControlName 与 value 一起使用
    • 使用属性出价 [value]="selectedSizeValue" 而不是 value = {{selectedSizeValue}}
    • 我从复选框中获取值并通过component.ts 中的函数将其分配给formControlName。就是这样。
    <form [formGroup]="variantForm" (ngSubmit) = "submit()">
        
          <input type="checkbox" [value]="selectedSizeValue" (change)="GetStats($event)" >
    
          <mat-radio-button value="{{sale_preis.value}}"><input type="text" #sale_preis formControlName ="sale_preis"></mat-radio-button>
        
          <button >save</button>
    </form>
    

    组件.ts

    selectedSizeValues: string;
    
    test: string ='';
    
    variantForm = new FormGroup({
        selectedSizeValueControl: new FormControl(),
        sale_preis: new FormControl()  });
    
    submit(){
           this.variantForm.value.selectedSizeValueControl = this.test;
      }
    GetStats(event: Event) {
        console.log(event);
        // @ts-ignore
        this.test = event.target.value;
        console.log(this.test);
      }
    

    【讨论】:

    • 您还需要检查 event.target.value 是否为 false 以 not assing 值,此外,您还需要使用 setValue 为 FormControl 赋予值
    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 2020-12-04
    • 2012-03-27
    • 2019-10-28
    相关资源
    最近更新 更多