2

I have a dropdown like this and I need to get the value on button click. but it always returns null. Need to get the cus_id value, without jquery

html file

<select #myselect>
    <option *ngFor="let title of titleArray" [attr.data-id]="title.cus_id" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

 <button (click)="save(myselect)">Save data</button>  

ts file

save(e:any){
  let cus_id=e.getAttribute('data-id');
  alert(cus_id)
}
rupesh
  • 21
  • 2

2 Answers2

1

We could create a two way binding and save the "selected" value option to a variable. Because this is a regular html select we use [(ngModel)] for two way binding.

Also, we also normally use camelCase for property names when using javascript title.Text -> title.text, myselect -> mySelect, title.Value -> title.value etc.

We can then access the variable selected for processing on (click) event which triggers function onSave() click in typescript part of the code.

I use ? when accessing property to conditionally check the prop exists first, this is just in case.

I use parseInt() to turn cus_id coming from template as string, back to a number.

If you don't plan on overwriting the variable prefer const over let.

Avoid any type e:any -> e: Event if possible (though not needed in my example).

If possible always prefer strong typing with interface or class, it will help you in the long run, that's the beauty of typescript - we strong type stuff.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  selected: string;

  titleArray: Title[] = [
    { cus_id: 1, text: 'Hancook', value: '123' },
    { cus_id: 2, text: 'I am legend', value: '456' },
    { cus_id: 3, text: 'Amber the turd', value: '789' },
  ];

  onSave() {
    console.log('now saving: ', this.selected);
    const arrayItem = this.titleArray.find((item) => item.cus_id === parseInt(this.selected));
    window.alert(JSON.stringify(arrayItem));
  }
}

export interface Title {
  cus_id: number;
  text: string;
  value: string;
}

Html

<select #myselect [(ngModel)]="selected">
  <option *ngFor="let title of titleArray" [value]="title?.cus_id">
    {{ title?.text }}
  </option>
</select>

<br />
<br />

<button (click)="onSave()">Save data</button>

This could be further simplified instead of using [value]="title?.cus_id" we could do [value]="title" and pass the obj title to variable selected, then we wouldn't have to search it from titleArray[] nor interpolate strings to number using parseInt() - but that's up to you.

Working example: https://stackblitz.com/edit/angular5-select-option-dropdown-qt4yvp?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Findex.html

Welcome to SO, nicely formatted question.

Joosep Parts
  • 5,372
  • 2
  • 8
  • 33
0

In Angular, we have two proper ways of managing forms, building reactive forms, and template-driven forms. I recommend you to check them out in Introduction to forms in Angular.

That said, I presume going for template-driven form is best for your particular use-case, and you ultimately want to get the cus_id property of the selected title.

Step 1: Import FormsModule

In your app/root module (or module where your component is declared), import FormsModule.

import { FormsModule } from "@angular/forms";

@NgModule({
  imports: [
    FormsModule, //  import here
    ...
  ],
  ...
})
export class AppModule { ... }

Step 2: Declare a data model for holding the current selection

export class MyComponent {
  // list of selectable options
  titleArray = [ ... ];

  selectedTitle?: MyComponent['titleArray']; //  this property will serve as the data model for the selection input
}

Step 3: Bind data model to view

Connect the data model to the view such that whenever the user selects a different option, the value of the data model will automatically update.

<select [(ngModel)]="selectedTitle">
    <option *ngFor="let title of titleArray" [ngValue]="title">
      {{title.Text}}
    </option>
</select>

<button (click)="onSave(selectedTitle)">Save data</button> 

Step 4: Process the selected option

Once the user hits save, you will now be able to process the actual object corresponding to the option that the user has currently selected.

// in the controller

onSave(title = this.selectedTitle) {
  console.log(title.cus_id);
}
Christian
  • 553
  • 4
  • 16