Issue
So I have a Dropdown Box
which contains data 'Dog', 'Lion', and 'Cat' so once I select the Dog it will not show in the Dropdown List how to achieve that, is it possible?
HTML:
<mat-form-field class="full-width" floatLabel="always" appearance="outline">
<mat-label>Choose Animal</mat-label>
<mat-select formControlName="animal">
<mat-option *ngFor="let items of animal" [value]="items.id">
{{items.animal}}
</mat-option>
</mat-select>
</mat-form-field>
TS:
ngOninit() {
this.getList()
}
getList() {
this.animalSVC.getListOfAnimal().subscribe((response: AnimalDTO) => {
this.animalObj = response;
this.animalDS = this.animalObj.items
})
}
For example, I select the lion in the list once I selected it will not show in the selected box again
Solution
If is not select multiple, you can use
<mat-option *ngFor="let food of foods"
[hidden]="food.value==form.get('food')?.value"
[value]="food.value"
>
{{food.viewValue}}
</mat-option>
And add the .css
mat-option[hidden]{
display:none
}
But if is multiple, we should give to the user an oportunity to "unselect"
For this we create a variable that change, when open/close the mat-select and when an option is unselected
oldValue:any[]=[]
<mat-select formControlName="foodMultiple" multiple
(openedChange)="oldValue=form.get('foodMultiple')?.value||[]"
>
<mat-option #option *ngFor="let food of foods"
(onSelectionChange)="!option.selected && unSelect(option.value)"
[hidden]="(form.get('foodMultiple')?.value||[]).indexOf(food.value)>=0
&& oldValue.indexOf(food.value)<0"
[value]="food.value"
>
{{food.viewValue}}
</mat-option>
</mat-select>
See that we use a template reference variable (the #option
) that allow us know if is or not selected option.selected
and pass to the function unSelect the value option.value
The construction (event)="condition && function()"
, makes that if the condition is not fullfilled, the function is not executed
unSelect(value:string)
{
this.oldValue=this.oldValue.filter(x=>x!=value)
}
So, if we unselect the next time we select it's remove.
NOTE: We can also not check if an option is deselected and don't change the oldValue variable, but them this not desapear if is checked again
NOTE2: I use the "classic" [hidden]
that you use normally in a typical select tag. It's the same if we use a class in the way [class.nodisplay]=...
and the .css mat-option.nodisplay
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.