Home > database >  How to get custom attribute value in angular 13
How to get custom attribute value in angular 13

Time:05-12

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

CodePudding user response:

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/app/app.component.html,src/app/app.component.ts,src/index.html

Welcome to SO, nicely formatted question.

CodePudding user response:

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, //            
  • Related