Selecting an option only Display Id not Name in angular 4

℡╲_俬逩灬. 提交于 2019-12-02 09:31:31

问题


I am working on Angular 4 Web API Here when selecting an option it will display packingtypename its working fine. but my problem is when clicking add button it will only save the packingtypeID i want Packing type id and packing type name Here i want to like this when selecting a PackingTypeName automatically pass their ID to API. which means when selecting a packing type Name and press add button the selected Name and its ID can be saved to DB. actually, I am new in angular. can anyone help please its a big help form me

my Html code is

  <label>Packing Type</label>
  <select class="form-control" id="PackingtypeName" placeholder="name" name="PackingtypeName" (change)="onSelect($event.target.value)" *ngIf="products">
   <option value="0" disabled>Please Select Packing type </option>
   <option *ngFor="let item of products" id={{item.PackingTypeID}} value={{item.PackingTypeID}}>{{item.PackingtypeName}}</option>
 </select>


<input type="button" value="Add Item"[disabled]="!itemdetails"  class="btn btn-success" (click)="addItems(newStockoutForm.value);newStockoutForm.reset()" />

my TS file

  addItems(value: any) {
 this.items = new IComboDetails(this.PackingTypeID, value.PackingtypeName, );

    console.log(this.PackingTypeID);
    alert(this.PackingTypeID);
    alert(value.PackingtypeName);// here show alert is PackingTypeID 
}

   onSelect(PackingTypeID: number) {
    alert(PackingTypeID);
    this._loginService.selectedpackingtypeid = PackingTypeID;
    this.PackingTypeID = PackingTypeID

回答1:


create a new variable in ts files name - PackingItem = {};

in html file change value={{item.PackingTypeID}} to [value]="item"

then in addItem() method check console.log(this.PackingItem);

Let me know if you have any doubt.




回答2:


Whatever is in the value for your option is what you will get on select.

Right now, you're setting it to just the ID, but you can set the value to the whole object if you want.

<option *ngFor="let item of products" id="{{item.PackingTypeID}}" [value]="item">{{item.PackingtypeName}}</option>

This will give you the whole item to play with on select instead of a single value.

Your onSelect will now look like:

onSelect(item: PackingType) {
  alert(`ID: ${item.PackingTypeID} - Name: ${item.PackingtypeName}`);
}

(Assuming your DTO is a PackingType type - I don't see any reference to the exact type you're using.. but I guess any would do. Either way, the object will be the actual item object).

Edit: added full option line, including mentioned fix for [input] of the value, and example of updated onSelect method. Don't phone and stack, peeps.



来源:https://stackoverflow.com/questions/57386843/selecting-an-option-only-display-id-not-name-in-angular-4

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