Remove selected option from dropdown after select

六眼飞鱼酱① 提交于 2021-02-10 16:38:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!