mercredi 19 juillet 2023

Angular (change) fires twice on checkbox

I have a parent + child components to pick tags from a checkbox list

ngFor does not work because a change event is attributed to this.tagList

the (change) is firing twice: one with the checkbox component, one with the change event

screenshot with console.log at checkbox click

enter image description here

I wanted the parent this.tagList populated with the tagList from (change)="onChange($event)" in child component

parent component

tagList: string[] = [];

 onTagChange(event: string[]) {

    this.error = '';

    this.tagList = event;

    console.log(event);

  }
<p>
        <span><button class="link" (click)="onPreviousClicked(3)">Back</button></span>
        &nbsp;<span><button class="link" (click)="onNextClicked(5)">Next</button></span>
    </p>

child component

@Output()
  change: EventEmitter<string[]> = new EventEmitter<string[]>();

  @Output()
  previous: EventEmitter<any> = new EventEmitter();

  @Output()
  next: EventEmitter<any> = new EventEmitter();

  tagList: string[] = [];

  tagListForm!: FormGroup;

  onChange(event: any) {

    const selectedTags = this.tagListForm.controls['tagList'] as FormArray;

    if (event.target.checked) {

      selectedTags.push(new FormControl(event.target.value));

    } else {

      const index = selectedTags.controls.findIndex(x => x.value === event.target.value);

      selectedTags.removeAt(index);

    }

    this.change.emit(this.tagListForm.value.tagList);

  }

  ngOnInit() {

    this.tagList = ['pix', 'nubank', 'uber', '99', 'super'];

    this.tagListForm = this.formBuilder.group({

      tagList: new FormArray([])

    });

  }
<form [formGroup]="tagListForm">

    <div *ngFor="let tag of tagList">

        <input [id]="tag" type="checkbox" formArrayName="tagList" [value]="tag" (change)="onChange($event)">
        <label [for]="tag"></label>

    </div>

</form>



Aucun commentaire:

Enregistrer un commentaire