Checkbox angular material checked by default

2020-06-08 02:40发布

I am trying to use an Angular Material checkbox, and set it by default as checked, but it is displayed as non-checked, what is wrong?

<mat-checkbox class = "example-margin" [(ngModel)] = obj.impresora> 
     <label>Printer</label> 
</mat-checkbox>

obj.impresora property is boolean

11条回答
我欲成王,谁敢阻挡
2楼-- · 2020-06-08 03:17

Make sure you have this code on you component:

export class Component {
  checked = true;
}
查看更多
小情绪 Triste *
3楼-- · 2020-06-08 03:18

For check it with ngModel, make a merge between "ngModel" and "value", Example:

 <mat-checkbox [(ngModel)]="myVariable"  value="1" >Subscribe</mat-checkbox>

Where, myVariable = 1

Greeting

查看更多
看我几分像从前
4楼-- · 2020-06-08 03:23

Set this in HTML:

    <div class="modal-body " [formGroup]="Form">
        <div class="">
            <mat-checkbox formControlName="a" [disabled]="true"> Display 1</mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="b"  [disabled]="true">  Display 2 </mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="c"  [disabled]="true">  Display 3 </mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="d"  [disabled]="true">  Display 4</mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="e"  [disabled]="true"> Display 5 </mat-checkbox>
        </div>
    </div>

Changes in Ts file

this.Form = this.formBuilder.group({
a: false,
b: false,
c: false,
d: false,
e: false,
});

Conditionvalidation in Ur Business logic

if(true){
this.Form.patch(a: true);
}
查看更多
等我变得足够好
5楼-- · 2020-06-08 03:24

You need to make sure the checked property to be true inside the component.ts

export class CheckboxComponent implements OnInit {
 checked = true;
}
查看更多
太酷不给撩
6楼-- · 2020-06-08 03:30

this works for me in Angular 7

// in component.ts
checked: boolean = true;

changeValue(value) {
    this.checked = !value;
}

// in component.html
<mat-checkbox value="checked" (click)="changeValue(checked)" color="primary">
   some Label
</mat-checkbox>

I hope help someone ... greetings. let me know if someone have some easiest

查看更多
登录 后发表回答