1

I am using angular 5 and I want to select multiple inputs from the dropdown and store the selected input into an array.

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

Here I am selecting multiple inputs correctly but how can I store selected values in an array?

Any help will be appreciated!

1
  • Wich input type do you want? Commented Jul 23, 2018 at 11:42

3 Answers 3

1

You can change option tag to below.

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

In you component,

array:any[]=[];

AddtoArray(feature:any){
    this.array.push(feature);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply use ngModel to add your selections to your model / array.

Kindly use something like below:-

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

For a working solution, have a look at the below stackblitz:-

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

Don't forget to press shift key to make multiple selections.

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

Comments

1

This can easily be achieved using (change) event as follows:

  <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>

And in .ts file

    var **yourArray**:string[];  // define array

    valueAdded(val){
    **yourArray**.Push(val);
    }

    This will add the selected options from dropDown in array named as **yourArray** 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.