Home > front end >  Angular Material Checkbox Default Value Selection
Angular Material Checkbox Default Value Selection

Time:11-28

there are 4 checkbox data in my modal. I want the previously selected data to be selected when the modal is closed and opened. How can I do this?

I added the selected data to a list, but unfortunately I could not make it selected.

Html Code;

<div >
          <div 
            *ngFor="let measurementTableList of getMeasurementPointIds()">
            <p>
              <mat-checkbox   [checked]="checkedMeasurmentPointId" value="measurementTableList"
                (change)="checkedMeasurmentPoint(measurementTableList, $event)">
                {{getMeasurementPointName(measurementTableList).measurementPointName}}</mat-checkbox>
            </p>
          </div>
        </div>


Ts Code;

 checkedMeasurmentPoint(selectedPoint: number, event: boolean) {

    if (event['checked']) {
      this.checkedMeasurmentPointId.push(selectedPoint)
    }
    else {
      const index = this.checkedMeasurmentPointId.indexOf(selectedPoint, 0);
      if (index > -1) {
        this.checkedMeasurmentPointId.splice(index, 1);
      }
    }

    this.ref.markForCheck();
  }

I tried [(ngModel)] but it didn't work

CodePudding user response:

Can you change the condition for "checked" as shown below,

[checked]="checkedMeasurmentPointId.includes(measurementTableList)"

CodePudding user response:

assign checked value to true on change function. [checked] value should be boolean, thus element of array checkedMeasurmentPointId, not array itself.

<div 
            *ngFor="let measurementTableList of getMeasurementPointIds(); let i = index">
            <p>
              <mat-checkbox   [checked]="checkedMeasurmentPointId[i]" 
              (change)="checkedMeasurmentPoint(measurementTableList,$event)">
   {{getMeasurementPointName(measurementTableList).measurementPointName}}</mat-checkbox>
            </p>
</div>
  • Related