2021年1月17日星期日

Angular Custom Form Control never make my Form dirty

I have created a custom form control but whenever the value changes, it does not mark the form dirty. I don't understand what should be done.

This is the code of my custom component :

    import { ThrowStmt } from '@angular/compiler';      import { Component, forwardRef, Input, OnInit, Output } from '@angular/core';      import { ControlValueAccessor, FormControl, NG_VALIDATORS, NG_VALUE_ACCESSOR } from '@angular/forms';      import { EventEmitter } from 'events';            @Component({        selector: 'app-multiple-checkbox',        templateUrl: './multiple-checkbox.component.html',        styleUrls: ['./multiple-checkbox.component.scss'],        providers: [          {            provide: NG_VALUE_ACCESSOR,            useExisting: forwardRef(() => MultipleCheckboxComponent),            multi: true          },          {            provide: NG_VALIDATORS,            useExisting: forwardRef(() => MultipleCheckboxComponent),            multi: true          }]      })      export class MultipleCheckboxComponent implements OnInit, ControlValueAccessor {              value = [];        disabled = false;              @Input() public options: { key, value }[];        @Output() haschanged = new EventEmitter();              onChange: any = (key) => {          this.haschanged.emit(key, this.value);        }              onTouched: any = () => { };              constructor() { }              validate({ value }: FormControl) {          const isNotValid = this.value.length === 0;          return isNotValid && {            invalid: true          };        }              ngOnInit(): void {        }              evaluate(event, key): void {          if (event.target.checked) {            this.value.push(key);          } else {            this.value.splice(this.value.findIndex(i => key === i), 1);          }                this.onTouched(this.value);          this.onChange(key, this.value);        }              isChecked(key): boolean {          return this.value.findIndex(e => e === key) > -1;        }              writeValue(value: any): void {          this.value = value;        }        registerOnChange(fn: any): void {          this.onChange = fn;        }        registerOnTouched(fn: any): void {          this.onChange = fn;        }        setDisabledState?(isDisabled: boolean): void {          this.disabled = isDisabled;        }            }  

The view is the following one :

    <div *ngFor="let option of options">          <label [attr.for]="option.key"></label>          <input [id]="option.key" type="checkbox" [checked]="isChecked(option.key)" [disabled]="disabled" (change)="evaluate($event, option.key)">      </div>    

What is missing to make the form dirty ?

https://stackoverflow.com/questions/65767159/angular-custom-form-control-never-make-my-form-dirty January 18, 2021 at 07:44AM

没有评论:

发表评论