0
votes

Hello everyone I'd like to send select option data from ngFor to Ts file but I tried [attr.value] , (ngModelChange) (change) all of them sent data's name only I want to send the all data which comes from ngFor

Html

<select [(ngModel)]="event" 
  class="selectpicker show-menu-arrow form-control show-tick" 
  data-style="btn-primary" (change)="doSomething(event)">

  <option *ngFor="let event of events|filter:search" 
    EventInput="{{event}}" 
    [attr.value]="event2">
    {{event.eventName}}
  </option>

</select>

TS

@Input('EventInput') EventInput: any;

doSomething(event) {
    console.log("optValue: ", event);
    //this.eventDetailsPageSend(event);
    console.log("input: ", this.EventInput);
}  

the optValue comes only name of event but I need the all data like id,etc(how comes from ngFor) so that I can push another page.I don't know if i should use Input or ngModelChange for being new with angular and this issue

Thank you.

1
You can't. The value of an option is a string only. Either you can use JSON.stringify to pass all your object into the value (which I don't recommend), or you use Array methods such as find, filter or reduce in your change function. - user4676340
Thank you for your quick reply , can you please give a brief example for change function - erdemgunenc
No I can't sorry, because I REALLY don't understand your code and your explanation. Plus, it's missing some parts of it, like your events property. - user4676340
Thank you for your quick reply. - erdemgunenc
Well no problem. If you want a start, try doing this in your change function : this.events.filter(ev => console.log(ev)) and see how you can compare your event variable to this ev - user4676340

1 Answers

3
votes

I dont know what you meen "I'd like to send select option data from ngFor to Ts file". So I'll assume what you want ;]. If you want to set the value of the <option> tag you should do

<select (change)="changed()" [(ngModel)]="selected">
   <option value=""></option>
   <option *ngFor="let event of events" [ngValue]="event">
     {{event.name}}
   </option>
</select>

In the component add

public selected = {};
public changed() {
  console.log(this.selected);
}

Dont forget to import FormsModule in AppModule @NgModule

Also I dont know where has setted your @Input decorator, but you can share data via @Input attributes only from Parent -> Child component, another thing is that in Angular2/4 there's no build in filter pipe anymore.

Edited