Search code examples
angularcheckboxangular-reactive-formsformgroups

Assign the value of a checkbox to a FormControlName (Angular)


I have a reactive form and want to take the value of a checkbox (not 'true' or 'false') and assign it to a formControlName (selectedSizeValueControl).

I have try some method but they do not work for me.

Can anyone please help?

The code:


    <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>

component.ts

selectedSizeValues: string;

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

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

  }

selectedSizeValueControl only takes TRUE or FALSE, I want it take the value of selectedSizeValue ( for ex: a string)

Thank you all!


Solution

  • I have succeeded with this.

    • Do not use formControlName along with value
    • Use the property bidning [value]="selectedSizeValue" instead of value = {{selectedSizeValue}}
    • I take the value from the checkbox and assign it to the formControlName through a function inside component.ts. That's it.
    <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>
    

    component.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);
      }