Angular 8/ Reactive Form - Converting result of checkbox event to a string value

前端 未结 2 537
面向向阳花
面向向阳花 2021-01-28 07:52

I have my Reactive form with field - Status (which can have values \'A\' or \'I\'):

this.form = this.formBuilder.group({
          result_info: this.formBuilder.         


        
相关标签:
2条回答
  • 2021-01-28 08:22

    You can retrieve the value like this:

    <input type="checkbox" (change)="test($event)"  value="helloworld">
    
    test(event) {
        console.log(event.target.value)
        return event.target.value
    }
    

    and then you assign the value of the property status to the result of the function test()

    0 讨论(0)
  • 2021-01-28 08:23

    a FormControl exist you has a input or not. I wrote yet in another answer (but I can not find it). Use a input with [ngModel] and (ngModelChange) to control the value of FormControl

        <input type="checkbox" [ngModel]="form.get('result_info2').value=='A'"
            (ngModelChange)="form.get('result_info2').setValue($event?'A':'B')"
           [ngModelOptions]="{standalone:true}">
    

    If you use mat-checkbox use checked and change

    <mat-checkbox [checked]="form.get('result_info').value=='A'"
                (change)="form.get('result_info').setValue($event.checked?'A':'B')">
    </mat-checkbox>
    

    In a FormArray it's the same imagine you has a form with a formArray, you defined in your .ts a function taht return the formArray

      get myformArray()
      {
        return this.form.get('formArray') as FormArray
      }
    

    And your form like

    <form [formGroup]="form">
        <div formArrayName="formArray">
            <div *ngFor="let group of myformArray.controls;let i=index" [formGroupName]="i">
                <input type="checkbox"  [ngModel]="group.get('status').value=='A'"
                (ngModelChange)="group.get('status').setValue($event?'A':'I')"
               [ngModelOptions]="{standalone:true}">status
                <input formControlName="action">
                 </div>
            </div>
    </form>
    

    See that you use an input "ngModel" to control the "check" and a input with formControlName to control the name

    You can be an example of all this in stackblitz

    0 讨论(0)
提交回复
热议问题