Home > Net >  Can we set value Yes when the checkbox is check and No when its not check
Can we set value Yes when the checkbox is check and No when its not check

Time:05-27

My thought I am new angular and i'm trying to develop a angular code that when the checkbox is checked i want to set value to Yes and when its not check i want to set it to No. I'm not using ngmodel i'm using formcontrolname. ill leave my code below

TScode

changeStatus(event:Event){
    const isChecked = (<HTMLInputElement>event.target).checked;
    console.log(isChecked)
}

html If i need to add any code please help me

<mat-checkbox matinput formControlName="substanceAbuseAlcohol" color="primary" (change)="changeStatus($event)">Alcohol</mat-checkbox><br>

form

this.patientPastHistoryForm = new FormGroup({
      patientId: new FormControl(this.clientId),
      substanceAbuseAlcohol: new FormControl(''),
});

CodePudding user response:

Stackblitz

Slightly hacky but following works using a variable in the html

  <mat-checkbox
    color="primary"
    (change)="
      patientPastHistoryForm.controls['substanceAbuseAlcohol'].setValue(
        saveValue.checked ? 'Yes' : 'No'
      )
    "
    #saveValue
  >
    Alcohol
  </mat-checkbox>

CodePudding user response:

As you're using mat-check box you can use the event change and the property checked

<mat-checkbox  
      (change)="patientPastHistoryForm.get('substanceAbuseAlcohol').setValue(
        $event.checked ? 'Yes' : 'No')"
      [checked]="patientPastHistoryForm.get('substanceAbuseAlcohol').value=='Yes'" >
   Alcohol
</mat-checkbox>

NOTE and Personal opinion: in a real Project or in a simple exercise create a custom form control using ControlValueAccesor should be only to create a more complex component, if only is change "the aspect" of a check-box I consider unnecessary (else you need use this "special checkbox" in several several components)

  • Related