问题
I have a scenario that i need to show dropdowns with selected or default values in view if there is any data from API. And i can add new dropdowns using add button. But i have to select value from drop downs only once so it will not repeated.
I am using ngFor loop to show this drop downs and i am using splice method to remove selected options from drop down. And i am facing a issue here that
Example: If i select car 1 from 1st drop down 1 and the 2nd drop down i can not see car 1 but if i go again to drop down 1 and change that option to car 2,
in drop down 2 i cannot see car 1 and car 2 options because splice deleting those option from that array.
<mat-select required formControlName="productTypeCode"
(selectionChange)="selectType($event.value)">
<mat-option>Select</mat-option>
<mat-option *ngFor="let type of newarrayvalues"
[value]="type.code">
{{type.name}}
</mat-option>
</mat-select>
PriorExperience -> form array for this dropdowns
for (let i = 0; i < this.InvestmentTypes.length; i++) {
for (let j = 0; j < this.PriorExperience.controls.length; j++) {
if (this.InvestmentTypes[i].code == this.financialDetailsForm.value.piExperience[j].productTypeCode) {
// this.removedValues.push(this.newarrayvalues[i])
this.InvestmentTypes.splice(i, 1);
}
}
I need to remove only selected values and if i change any dropdown value that should only removed from that array
Please help me with this.
回答1:
Your problem is that they are sharing the same data.
If I were you, I would create component that takes the value of the array as and @Input. then in that component put the logic of the deleting the option. Then in the parent component you are going to render with a foorLoop that component you have created.
回答2:
because splice deleting those option from that array.
don't splice the actual object instead
Create a Array of objects
with available data, object should be like
{value: " yourValue", selected: "booleanValue" }
If the value is selected in any of the dropdowns just change the boolean
to true.
<mat-select required formControlName="productTypeCode"
(selectionChange)="selectType($event.value)">
<mat-option>Select</mat-option>
<ng-container *ngFor="let type of newarrayvalues">
<mat-option *ngIf="type.selected"
[value]="type.value">
{{type.value}}
</ng-container>
</mat-select>
来源:https://stackoverflow.com/questions/57849385/remove-selected-option-from-dropdown-after-select