我有一个选择控件,我希望它在选项更改时传递所选选项的ID,但不知道该怎么做。
<select id="companydropdown" (change)="getcompanyid($event)">
<option *ngFor="let company of filteredCompanies" value={{company.companyName}}
id={{company.id}}>
{{company.companyName}}
</option>
</select>
答案 0 :(得分:0)
将其传递到哪里?喜欢而不是companyName
?传递的是选项值,您只需将值更改为id:
<select id="companydropdown" change="getcompanyid($event)">
<option *ngFor="let company of filteredCompanies" value={{company.id}} id={{company.id}}>
{{company.companyName}}
</option>
</select>
答案 1 :(得分:0)
您可以使用“ $ event.target.value”访问选定的值。为此,必须将预期值分配给“”标记的“值”属性。
<select id="companydropdown" (change)="getcompanyid($event.target.value)">
<option *ngFor="let company of filteredCompanies" value="{{company.id}}">
{{company.companyName}}
</option>
</select>
注意事件处理程序和
中的更改有关完整示例,请参见stackblitz: https://stackblitz.com/edit/select-option-to-event
答案 2 :(得分:0)
执行此操作的最佳方法是使用ReactiveFormsModule。首先,您需要声明要建立的FormBuilder控制器,然后声明您的元素(选项)的数组,如以下示例所示:
import { Component } from '@angular/core';
import { FormBuilder, Validators } from "@angular/forms";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isSubmitted = false;
// City Names
City: any = ['Florida', 'South Dakota', 'Tennessee', 'Michigan', 'New York']
constructor(public fb: FormBuilder) { }
/*########### Form ###########*/
registrationForm = this.fb.group({
cityName: ['', [Validators.required]]
})
// Getter method to access formcontrols
get cityName() {
return this.registrationForm.get('cityName');
}
/*########### Template Driven Form ###########*/
onSubmit() {
this.isSubmitted = true;
if (!this.registrationForm.valid) {
return false;
} else {
alert(JSON.stringify(this.registrationForm.value))
}
}
}
然后您可以在模板上迭代选项:
<select class="custom-select" (change)="changeCity($event)" formControlName="cityName">
<option value="" disabled>Choose your city</option>
<option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
</select>
这是一个很好的完整教程,可满足您的需求: https://www.positronx.io/angular-7-select-dropdown-examples-with-reactive-forms/
也请阅读文档以更好地了解ReactiveForms,也许需要花费更多时间,但值得:https://angular.io/guide/reactive-forms
答案 3 :(得分:0)
这应该为您提供更改事件处理程序上的id
event.currentTarget.options[event.currentTarget.options.selectedIndex].id