如何为 mat-checkbox 分配自定义值?

San*_*mar 1 angular-material-7

我想用 mat-checkbox 附加我的状态字段,并希望以字符串的形式获取值,就像我们用来获取 Material-1 一样。

我正在寻找ng-true-value="'ACTIVE'" ng-false-value="'INACTIVE'"Material-7 中的替代品。

G. *_*ter 9

您可以通过使用 的value属性MatCheckbox并监听更改来实现这一点。例如:

HTML

<mat-checkbox [value]="falseValue" (change)="checkboxChange($event.source, $event.checked)">
  Check me!
</mat-checkbox>
Run Code Online (Sandbox Code Playgroud)

TS

falseValue = 'No'
trueValue = 'Yes';

checkboxChange(checkbox: MatCheckbox, checked: boolean) {
  checkbox.value = checked ? this.trueValue : this.falseValue;
}
Run Code Online (Sandbox Code Playgroud)

您也可以将其实现为指令:

TS

import {Directive, Input} from '@angular/core';
import {MatCheckbox} from '@angular/material/checkbox';

@Directive({
  selector: 'mat-checkbox[checkboxValue]',
  exportAs: 'checkboxValue'
})
export class CheckboxValueDirective {

  @Input('checkboxValue') checkbox: MatCheckbox;
  @Input() falseValue: string = '0';
  @Input() trueValue: string = '1';

  ngOnInit() {
    this.checkbox.value = this.checkbox.checked ? this.trueValue : this.falseValue;
    this.checkbox.registerOnChange((checked: boolean) => {
      this.checkbox.value = checked ? this.trueValue : this.falseValue;
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

<mat-checkbox #checkbox [checkboxValue]="checkbox" trueValue="Yes" falseValue="No" [checked]="true">
  Check me!
</mat-checkbox> 
Run Code Online (Sandbox Code Playgroud)

这是 StackBlitz 上的指令示例:https ://stackblitz.com/edit/angular-aapsr6 ? file = app/checkbox-value-directive.ts