首页 文章

选择多个输入并以角度5存储到数组中

提问于
浏览
1

我正在使用角度5,我想从下拉列表中选择多个输入并将所选输入存储到数组中 .

<select multiple  class="form-control " name="fea" ngModel size="3" >
  <option *ngFor="let feature of features | async" [ngValue]="feature">
       {{ feature.name }}
  </option>
</select>

这里我正确选择了多个输入但是如何在数组中存储选定的值?

任何帮助将不胜感激!

3 回答

  • 1

    您只需使用 ngModel 将您的选择添加到模型/数组中 .

    请使用以下内容: -

    <select multiple class="form-control " name="fea" ngModel size="3" [(ngModel)]="selectedFeatures">
      <option *ngFor="let feature of features" [ngValue]="feature">
           {{ feature.name }}
      </option>
    </select>
    

    有关工作解决方案,请查看下面的stackblitz: -

    https://stackblitz.com/edit/angular-hyazbe?file=src%2Fapp%2Fapp.component.html

    不要忘记按 shift 键进行多项选择 .

    PS: I have not used the async pipe in the code but it should work fine with it too.

  • 1

    您可以将选项标签更改为以下 .

    <option *ngFor="let feature of features | async" [ngValue]="feature" (click)="AddtoArray(feature.name)">
           {{ feature.name }}
      </option>
    

    在你的组件中,

    array:any[]=[];
    
    AddtoArray(feature:any){
        this.array.push(feature);
    }
    
  • 0

    这可以使用(更改)事件轻松实现,如下所示:

    <select multiple  class="form-control " name="fea" [(ngModel)]="model" (change)="valueAdded(model)">
          <option *ngFor="let feature of features | async" [ngValue]="feature">
               {{ feature.name }}
          </option>
        </select>
    

    在.ts文件中

    var **yourArray**:string[];  // define array
    
        valueAdded(val){
        **yourArray**.Push(val);
        }
    
        This will add the selected options from dropDown in array named as **yourArray**
    

相关问题