Right now I render for every selected element inside my multiselect angular material selectbox.
The rendering works when I am selecting an element inside it. But when I deselect one it does just keeps adding.
My guess is that I have to set a property like deselect or something but I am not sure, could someone help me out?
HTML:
<mat-select [formControl]="person" required>
<mat-option>--</mat-option>
<mat-option *ngFor="let person of person" [value]="person" (click)="getPerson()">
{{person.name}}
</mat-option>
</mat-select>
<div *ngFor="let person of personsArray">
<div class="card" >
<div class="card-body dl-card-body-no-padding-bottom" >
//element to render
</div>
</div>
TS:
getPerson(){
this.personsArray.push(this.form.controls.person.value)
}
In your HTML for your mat-select you will need to include the multiple attribute.
Also, make sure you appropriately name the arrays to store the items from the source array and the selected array. It's rather confusing to refer to person twice in the select template.
You need to pass data into the selection handler. This is done as shown in the amended HTML below:
<mat-select [formControl]="person" required multiple>
<mat-option>--</mat-option>
<mat-option
*ngFor="let person of personsArray"
[value]="person"
(click)="getPerson(person)"
>
{{ person.name }}
</mat-option>
</mat-select>
In your component code, include an array for the source array and selected items array:
form: any;
person = new FormControl('');
personsArray: Person[] = [
{ name: 'bob' },
{ name: 'dave' },
{ name: 'fred' },
];
selectedPersonsArray: Person[] = [];
constructor() {
this.form = new FormGroup({
person: new FormControl(''),
});
}
In your selection handler, you need to handle the appending and removal of items depending on whether they already exist (remove) or do not exist (append) in the select items array:
getPerson(val: Person) {
console.log('selected person = ' + val.name);
const person: Person = this.selectedPersonsArray.find(
(p) => p.name === val.name
);
console.log('sel person=' + person?.name);
if (!person) this.selectedPersonsArray.push(val);
if (person?.name)
this.selectedPersonsArray = this.selectedPersonsArray.filter(
(p) => p.name !== val.name
);
}
The person object is just an interface similar to this:
export interface Person {
name: string;
}
The above is sufficient to allow selected or un-selected items within multi-selection drop down to display within the rendered list.