Checkbox angular material checked by default

前端 未结 11 2376
傲寒
傲寒 2021-02-11 19:37

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?



        
相关标签:
11条回答
  • 2021-02-11 20:28

    Make sure you have this code on you component:

    export class Component {
      checked = true;
    }
    
    0 讨论(0)
  • 2021-02-11 20:28

    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:32

    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)
  • 2021-02-11 20:36

    The chosen answer does work however I wanted to make a comment that having 'ngModel' on the html tag causes the checkbox checked to not be set to true.

    This occurs when you are trying to do bind using the checked property. i.e.

    <mat-checkbox [checked]='var' ngModel name='some_name'></mat-checkbox>
    

    And then inside your app.component.ts file

    var = true;
    

    will not work.

    TLDR: Remove ngModel if you are setting the checked through the [checked] property

        <mat-checkbox [checked]='var' name='some_name'></mat-checkbox>
    
    0 讨论(0)
  • 2021-02-11 20:38

    You can use

    <mat-checkbox [attr.checked] = "myCondition ? 'checked' : null">

    if the checked attribute is set to null, it gets removed from the html tag

    or you can use Vega's anwser which should work too (mine is a completion that can be usefull if you don't want to link it with ngModel)

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