Not able to reset the form with mat chips and mat auto-complete - Angular Reactive forms

Discussão em 'Angular' iniciado por Anil Kumar Reddy A, Janeiro 17, 2025.

  1. I'm using material design for creating a form where I'm using input field with mat-chips and mat-autocomplete, but when I tried to reset the form using form.reset(); it's not working;

    HTML

    <mat-form-field class="demo-chip-list">
    <mat-chip-list #chipList2>
    <mat-chip *ngFor="let state of selected"
    [selectable]="selectable"
    [removable]="removable"
    (remove)="remove(state)">
    {{state}}
    <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input #input placeholder="Pick a state..."
    [matChipInputFor]="chipList2"
    [matChipInputAddOnBlur]="addOnBlur"
    (matChipInputTokenEnd)="add($event)"
    [matAutocomplete]="auto"
    [formControl]="stateCtrl"/>
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="add($event);
    input.value = ''">
    <mat-option *ngFor="let state of filteredStates | async"
    [value]="state">
    {{ state }}
    </mat-option>
    </mat-autocomplete>
    </mat-chip-list>
    </mat-form-field>
    <button mat-button (click)="clear()">clear</button>


    TS

    color = 'primary';
    selectable = true;
    removable = true;
    addOnBlur = true;
    @ViewChild('auto') auto: ElementRef;
    states = [
    'Alabama', 'Alaska', 'Arizona', 'Arkansas'
    ];
    stateCtrl: FormControl;
    filteredStates: any;
    selected: string[] = [
    'Illinois', 'Missouri'
    ];

    constructor() {
    this.stateCtrl = new FormControl();
    this.filteredStates = this.stateCtrl.valueChanges.pipe(
    startWith(null),
    map((name: string) => this.filterStates(name))
    );
    }
    filterStates(val: string) {
    const matches = val ? this.states.filter(s => new RegExp(`^${val}`,
    'gi').test(s))
    : this.states;
    return matches.filter(x => !this.selected.find(y => y === x));
    }

    add(event: MatAutocompleteSelectedEvent): void {
    if (!event.option) { return; }
    const input = event.source;
    const value = event.option.value;

    if ((value || '').trim()) {
    this.selected.push(value.trim());
    this.stateCtrl.setValue('');
    }
    }
    remove(state: string): void {
    const index = this.selected.indexOf(state);

    if (index >= 0) {
    this.selected.splice(index, 1);
    }
    }
    clear(){
    this.stateCtrl.setValue('');
    }


    Even when I try to reset using form.controlName.setValue(''); then also it's not working.

    stackblitz Link: https://stackblitz.com/edit/angular-material2-issue-jn5dzm

    Continue reading...

Compartilhe esta Página