Ng2-select: How I can reset selected value or values from my component?

Created on 18 Jan 2017  Â·  8Comments  Â·  Source: valor-software/ng2-select

I do not have any way for reset selected value in ng2-select implementing reset button in form

Most helpful comment

If you want reset selected value programatically, it works for me:

in html:

<ng-select #chosenuser [ngClass]="{'browser-default': true, 'bootstrapButton': true, 'btn': false}"
                   [allowClear]="true"
                   [items]="sourceusers"
                   (selected)="changeSourceUser($event)"
                   (removed)="changeSourceUser($event)"
                   (typed)="typeSourceUser($event)"
                   placeholder="Choose user">

in component:

@ViewChild('chosenuser') public ngSelect: SelectComponent;
.....
reset(){
    this.ngSelect.active = [];
    .....
}

All 8 comments

:+1:

:thumbsdown: :cry:

If you want reset selected value programatically, it works for me:

in html:

<ng-select #chosenuser [ngClass]="{'browser-default': true, 'bootstrapButton': true, 'btn': false}"
                   [allowClear]="true"
                   [items]="sourceusers"
                   (selected)="changeSourceUser($event)"
                   (removed)="changeSourceUser($event)"
                   (typed)="typeSourceUser($event)"
                   placeholder="Choose user">

in component:

@ViewChild('chosenuser') public ngSelect: SelectComponent;
.....
reset(){
    this.ngSelect.active = [];
    .....
}

This work, but when field is required it still has class ng-valid. How to change class to ng-invalid?

how to reset value without using @ViewChild .
I am programattically creating ng-select html control in a table of rows based on table from database.
so it is not possible for me to give name to view child using #tag in html.

@hemantoswal you could use boolean flag

<ng-select *ngIf="flag">...
flag = true;

// reset
this.flag = false;
setTimeout(() => {this.flag = true;})

This is the pseudo-code, but i think you get the idea

@tytskyi
Hello,
Very nice reply.
it solved my problem and yet I come to know that i can reset value of form control in following way

//reset
setTimeout(()=>{
this.formGroup.get('controlName') .reset( );
});
// formGroup is your FormGroup control and control name is FormControl in that group.
// reset function also resets valid, dirty, pristine classes of that element.

Thank you so much.

following on from the answer supplied by @macqbat I found that you can also just call the remove function

@ViewChild('chosenuser') public ngSelect: SelectComponent;
.....
reset(value: any){
    this.ngSelect.remove(value);
    .....
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Kiwi15 picture Kiwi15  Â·  4Comments

bissolli picture bissolli  Â·  6Comments

Hasnain-Bukhari picture Hasnain-Bukhari  Â·  3Comments

denghuiquan picture denghuiquan  Â·  3Comments

sharok picture sharok  Â·  4Comments