如何获得Angular 13中的自定义属性值

发布于 2025-01-28 00:14:25 字数 460 浏览 1 评论 0原文

我有这样的下拉列表,我需要在按钮上获得值。但是它总是返回零。需要获取CUS_ID值,而无需jQuery

HTML文件

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝天白云 2025-02-04 00:14:25

我们可以创建两种绑定,并将“选定”值选项保存到变量。因为这是常规的HTML选择,我们使用[(ngmodel)]进行两种绑定。

另外,使用JavaScript title.text.text - &gt; title.textmySelect - &gt; mySelecttitle.value - &gt; title.Value等。

然后,我们可以访问变量选择上处理(单击)事件,触发功能onsave() /代码>单击代码的打字稿部分。

我使用访问属性以有条件地检查道具时首先存在,以防万一。

我使用parseint()cus_id从模板作为字符串,回到一个数字。

如果您不打算覆盖变量优先const而不是

避免任何类型e:任何 - &gt; e:事件如果可能的话(尽管在我的示例中不需要)。

如果可能的话,始终更喜欢使用接口的强键打字,从长远来看,它将为您提供帮助,这就是打字稿的美 - 我们强大的东西。

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

这可以进一步简化而不是使用[value] =“ title?.cus_id”我们可以做[value] =“ title”并传递OBJ title to variable 选择,那么我们就不必从titlearray []或使用parseint() interpallate()代码> - 但这取决于您。

工作示例: https://stackblitz.com/edit/Edit/EDIT/Angular5-select-option-option-dropdown-qt4yvp?file=src%2fapp%2fapp%2fapp%2fapp%2fapp; 。

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.

素手挽清风 2025-02-04 00:14:25

在Angular中,我们有两种正确的方式来管理形式,构建反应性形式和模板驱动的形式。我建议您在

也就是说,我认为要使用模板驱动的表单最适合您的特定用例,并且您最终希望获得所选title> titlecus_id属性。

步骤1:导入formsModule

在您的应用/root模块中(或声明组件的模块),导入formsmodule

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

@NgModule({
imports: [
FormsModule, //

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文