How to remove the selected tags tag-input ngx-chips from code behind?

1k Views Asked by At

When i try to clear the model , it works first time but then it just doesn't clear the tags. HTML

<tag-input theme='bootstrap'  id="test" [ngModel]="tagsSelected" [onlyFromAutocomplete]="true"   [clearOnBlur]="true" [maxItems]= maxProductModels  (onAdd)="onModelAdded($event)" (onRemove)="onModelRemoved($event)">
      <tag-input-dropdown [showDropdownIfEmpty]="true"  placeholder=""
             [autocompleteItems]="sampleData">
      </tag-input-dropdown>
  </tag-input>

In the code behind , i am trying to clear the model in my typescript file this.tagsSelected = [];

This works for the first time but later i doesn't seem to be working

1

There are 1 best solutions below

0
Alidad On

Not sure how you are clearing your tagsSelected, but first I would suggest to make tagsSelect 2way binding [(ngModel)]="tagsSelected"

<tag-input theme='bootstrap'  id="test" [(ngModel)]="tagsSelected" [onlyFromAutocomplete]="true"
           [clearOnBlur]="true" [maxItems]= "5"  (onAdd)="onModelAdded($event)" (onRemove)="onModelRemoved($event)">
    <tag-input-dropdown [showDropdownIfEmpty]="true"  placeholder=""
                        [autocompleteItems]="sampleData">
    </tag-input-dropdown>
</tag-input>

<button (click)="clear()">Reset</button>
<button (click)="pop()">pop</button>
<button (click)="add()">add</button>

Component:

import {Component, OnInit} from '@angular/core';
import {TagModel} from 'ngx-chips/core/accessor';

@Component({
    selector: 'app-ngx-chips',
    templateUrl: './ngx-chips.component.html',
    styleUrls: ['./ngx-chips.component.css']
})
export class NgxChipsComponent implements OnInit {
    tagsSelected: any [] = [];
    sampleData: any;

    constructor() {
        this.sampleData = [
            {display: 'A1', value: 'aA4'},
            {display: 'A2', value: 'aA3'},
            {display: 'A3', value: 'aA2'},
            {display: 'A4', value: 'aA1'},
        ];
    }

    clear = () => {
        this.tagsSelected = [];
    }

    add = () => {
        const display = 'x_' + this.tagsSelected.length;
        this.tagsSelected.push({display, value: display});
    }

    pop = () => {
        this.tagsSelected.pop();
    }

    ngOnInit(): void {
    }

    onModelAdded = ($event: TagModel) => {
        console.log(`$event`, $event);
    }

    onModelRemoved = ($event: TagModel) => {
        console.log(`$event`, $event);
    }

}