【问题标题】:Mat-checkbox [checked]="false" does not work angular 6 [closed]Mat-checkbox [checked]="false" 不起作用 Angular 6 [关闭]
【发布时间】:2019-05-13 20:23:19
【问题描述】:

使用 checked 输入属性时,我的 mat-checkbox 不会更改值。

<mat-checkbox [checked]="false"
              formControlName="value1">Value1
</mat-checkbox>
  • 请解释checked 输入属性的用法,即:将布尔变量传递给 checked 输入属性?

  • 有没有办法使用FormControl进行默认选择 不需要在组件上使用checked 输入属性?

【问题讨论】:

  • 获取您的原始代码,并删除 [checked] 字段。该复选框应默认为真/假,具体取决于 value1 是什么。

标签: html angular checkbox


【解决方案1】:

checked 属性是一个布尔输入,需要 truefalse

@输入() 检查:布尔值

https://material.angular.io/components/checkbox/api

使用[checked]="true" 将导致选中框,[checked]="false" 将导致未选中框。


下面是FormControl的检查方法

<mat-checkbox [formControl]="checkboxFormControl">Checked Using FormControl</mat-checkbox>

checkboxFormControl = new FormControl(true);

将在FormGroup 中使用FormControl 检查以下内容

<form [formGroup]="myForm">
  <mat-checkbox formControlName="checked">Checked Using formControlName in FormGroup</mat-checkbox>
</form>

  myForm = new FormGroup({
    checked: new FormControl(true)
  })

堆栈闪电战

https://stackblitz.com/edit/angular-tylt6w?embed=1&file=app/checkbox-overview-example.ts

【讨论】:

    【解决方案2】:

    我认为这段代码可以帮助你 html:

     <form [formGroup]="form">
              <mat-checkbox id="Value1" class="Value1" color="primary"
                            formControlName="Value1">Value1</mat-checkbox>
            </form>
            <pre>{{form.value | json}}</pre> 
    

    ts:

    this.form = this.fb.group({
             Value1: [false],
            });
    

    【讨论】:

    • 谢谢你的回答,但还是不行
    • @tcw9721 可以告诉我发生了什么或发生了错误?因为这段代码在系统上运行正常。
    • 我收到警报It looks like you're using ngModel on the same form field as formControlName. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7. For more information on this, see our API docs here:
    • @tcw9721 如果您在复选框上使用 ngModel,请删除它,因为反应式表单和模板驱动的两种不同的角度方法都不同。我正在与您分享有效的链接,请检查link
    【解决方案3】:

    使用双向绑定:

    <mat-checkbox  [(ngModel)]="checked">{{checked}}</mat-checkbox>
    

    现在在您的 component.ts 中,'checked' 具有复选框的值

    【讨论】:

      猜你喜欢
      • 2020-04-28
      • 2019-11-25
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多