Checkbox angular material checked by default

前端 未结 10 1529
猫巷女王i
猫巷女王i 2021-02-11 19:47

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?



        
相关标签:
10条回答
  • 2021-02-11 20:25
    // in component.ts
    checked: boolean = true;
    indeterminate:boolean = false;
    disabled:boolean = false;
    label:string;
    
    onCheck() {
        this.label = this.checked?'ON':'OFF';
    }
    
    // in component.html`enter code here`
    <mat-checkbox class="example-margin" [color]="primary" [(ngModel)]="checked" [(indeterminate)]="indeterminate" [labelPosition]="after" [disabled]="disabled" (change)="onCheck()">
                        {{label}}
                      </mat-checkbox>
    

    The above code should work fine. Mat checkbox allows you to make it checked/unchecked, disabled, set indeterminate state, do some operation onChange of the state etc. Refer API for more details.

    0 讨论(0)
  • 2021-02-11 20:34

    If you are using Reactive form you can set it to default like this:

    In the form model, set the value to false. So if it's checked its value will be true else false

    let form = this.formBuilder.group({
        is_known: [false]
    })
    

    //In HTML

     <mat-checkbox matInput formControlName="is_known">Known</mat-checkbox>
    
    0 讨论(0)
  • 2021-02-11 20:37

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

    export class CheckboxComponent implements OnInit {
     checked = true;
    }
    
    0 讨论(0)
  • 2021-02-11 20:38

    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

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