当前位置:Gxlcms > 数据库问题 > [Angular] Create a ng-true-value and ng-false-value in Angular by controlValueAccessor

[Angular] Create a ng-true-value and ng-false-value in Angular by controlValueAccessor

时间:2021-07-01 10:21:17 帮助过:3人阅读

‘@angular/forms‘; @Directive({ selector: ‘input[type=checkbox][trueFalseValue]‘, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TrueFalseValueDirective), multi: true } ] }) export class TrueFalseValueDirective implements ControlValueAccessor { @Input() trueValue = true; @Input() falseValue = false; private propagateChange = (_: any) => { }; 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 { // model -> view if (obj === this.trueValue) { // this.elementRef.nativeElement.checked = true; 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 { } }

 

How to use:

      <input type="checkbox" formControlName="lovingAngular"
        trueFalseValue
        trueValue="yes" falseValue="nope"
        > loving Angular?

 

[Angular] Create a ng-true-value and ng-false-value in Angular by controlValueAccessor

标签:his   int   api   ons   sdi   imp   pre   listen   from   

人气教程排行