Angular checkbox check

Viewed 566

I'm writing a code where if a material is approved, it will appear with a blue mark next to it without me checking the checkbox. I tried the method below but, I can still check the box, it does not come already checked. This is what it should look like when the page is opened:

enter image description here

What am I doing wrong?

HTML:

<ng-container matColumnDef="IsApproved">
                                    <th mat-header-cell *matHeaderCellDef> Ürün Onay Durumu </th>
                                    <td mat-cell *matCellDef="let row; let i = index">
                                        <mat-checkbox
                                            [(ngModel)]="row.IsApproved" [ngModelOptions]="{standalone: true}"
                                            binary="true"(onChange)="onChecked($event)"> Approved
                                        </mat-checkbox>
                                    </td>
                                </ng-container>

TS Code:

export class ManufacturerDetailComponent {
displayedColumns: string[] = [
        "IsApproved",
    ];
    IsApproved: boolean=false;
accept(){
        this.onChecked(true)
       }
   
       onChecked(e: any){
         this.IsApproved = true;
       }
}
3 Answers

Use the [checked] property to show the checked state at start.

<mat-checkbox
     [(ngModel)]="row.IsApproved" [ngModelOptions]="{standalone: true}"
      binary="true"(onChange)="onChecked($event)"
      [checked]="row.IsApproved"> Approved
</mat-checkbox>

Have you set the property IsApproved to true?

Assuming you have dataSource something like

dataSource = [
 {
   "IsApproved": true, //Set this to true so that row.IsApproved will mark the checkbox as checked
   ...
 },
 ...
]

[(ngModel)] is "Template Forms". It is not supposed to get values, but objects.

Here you have 2 options. Either you make no use of the template forms and use the "value" input property of the checkbox item to set the value like this:

<mat-checkbox [checked]="row.IsApproved" binary="true (onChange)="onChecked($event)">
 Approved
</mat-checkbox>

Or you use the cleanest approach with [(ngModel)] but you have to send an object and not a value.

Related