如何将boolean更改为mat复选框的字符串?(Angular Material)

问题描述 投票:0回答:2

当我点击材料复选框(mat-checkbox)时,如何将布尔值(true false)更改为字符串。

我有一个输入https://stackblitz.com/edit/angular-ng-true-false的例子。所以我使用相同的代码,但我将输入复选框更改为材料复选框。我包括材料模块。

我的代码与材料复选框

import {
    Directive,
    Input,
    forwardRef,
    HostListener,
    ElementRef,
    Renderer2
} from '@angular/core';
import {
    ControlValueAccessor,
    NG_VALUE_ACCESSOR,
    NgControl
} from '@angular/forms';

@Directive({
    selector: 'input[type="checkbox"][trueFalseValue]',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => TrueFalseValueDirective),
            multi: true
        }
    ]
})
export class TrueFalseValueDirective implements ControlValueAccessor {
    private propagateChange = (_: any) => { };
    @Input() trueValue = true;
    @Input() falseValue = false;

    constructor(private elementRef: ElementRef, private renderer: Renderer2) { }

    @HostListener('change', ['$event'])
    onHostChange(ev) {
        this.propagateChange(ev.target.checked ? this.trueValue : this.falseValue);
    }

    writeValue(obj: any): void {
        if (obj === this.trueValue) {
            this.renderer.setProperty(this.elementRef.nativeElement, 'checked', true);
        } else {
            this.renderer.setProperty(this.elementRef.nativeElement, 'checked', false);
        }
    }

    registerOnChange(fn: any): void {
        this.propagateChange = fn;
    }

    registerOnTouched(fn: any): void { }

    setDisabledState?(isDisabled: boolean): void { }
}
import { Component, OnInit, Inject, Input, Output, EventEmitter } from '@angular/core';
   
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';


@Component({
  selector: 'app-agreements',
  templateUrl: './agreements.component.html',
  styleUrls: ['./agreements.component.scss']
})

export class AgreementsComponent implements OnInit {

  myForm: FormGroup;

  constructor( private fb: FormBuilder, ) {
   
  }

  ngOnInit() {

    this.myForm = new FormGroup({
     
      emailAgreement: new FormControl('Y'),
     
    });

    this.myForm = this.fb.group({
      
      emailAgreement: ['']
    });

  }
 


}
<mat-checkbox class="checkbox-mat" 
              formControlName="emailAgreement" trueFalseValue trueValue="Y" falseValue="N">Agreement to be contacted</mat-checkbox>

但我希望它有角度的材料工作。我将不胜感激任何帮助。谢谢。

angular angular-material
2个回答
1
投票

为了补充我的答案,做一个自定义表单控件很容易,只需实现controlValueAntecesor。

在这种情况下,它只是写

@Component({
  selector: 'true-false-value',
  template:`<mat-checkbox #id [ngModel]="valor" 
                (ngModelChange)="change(id)">
                <ng-content></ng-content>
            </mat-checkbox>`
,  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => TrueFalseValueComponent),
      multi: true
    }
  ]
})
export class TrueFalseValueComponent implements ControlValueAccessor {
  private propagateChange = (_: any) => {};
  @Input() trueValue = true;
  @Input() falseValue = false;
  valor:any;

  constructor() {}

//when change the model, call to function "propagateChange" with the correct value
change(id:any)
{
  this.valor=id.checked;
  this.propagateChange(this.valor? this.trueValue:this.falseValue)
}

 //At first, we received a value, we must change the "aparence" of our component
  writeValue(obj: any): void {
    this.valor=(obj === this.trueValue);
  }

  //here we say to Angular that we're going to use the function
  //this.propagateChange when a change happends
  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {}

  setDisabledState?(isDisabled: boolean): void {}
}

1
投票

如果要将复选框值存储为表单中的字符串,请使用复选框更改事件将字符串值应用于复选框的表单控件:

HTML

<mat-checkbox (change)="checkboxChange($event.checked)" [formControl]="control">Check me!</mat-checkbox>

TS

export class CheckboxStringValueFormExample {
  setValueOptions = {
    onlySelf: true, 
    emitEvent: false, 
    emitModelToViewChange: false, 
    emitViewToModelChange: false
  }

  control = new FormControl();

  checkboxChange(checkboxValue) {
    this.control.setValue(checkboxValue ? 'Y' : 'N', this.setValueOptions);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.