我有一个下拉选择,在这里单击按钮,我需要控制台选中的文本(绿色..)和选中的值(1 ..),我尝试了ngmodel,但是我只能捕获值,也可以捕获空选项在选择字段中显示。这是下面的代码,
<select>
<option *ngFor="let status of statusdata" value="{{status.id}}">{{status.name}}</option>
</select>
<button type="submit" (click)="register()" class="btn btn-primary mr-1">Register</button>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
dotsh:any;
hoverIndex:number = -1;
groups:any;
test:any;
constructor(private formBuilder: FormBuilder) {
}
onHover(i:number){
this.hoverIndex = i;
}
columns = ["name", "Items","status"];
ngOnInit() {
this.test = false;
this.statusdata = [{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}];
}
register(){
console.log('selected Value');
console.log('selected name');
}
}
答案 0 :(得分:1)
如果要在选择对象时将整个对象存储为一个值,则可以尝试以下操作:
<select [(ngModel)]="value">
<option *ngFor="let status of statusdata" [ngValue]="status">
{{status.name}}</option>
</select>
然后在您的组件中声明变量值,然后将其保留为未定义状态或将其分配给所需的值(它必须是整个对象)。例如:
export class HomeComponent implements OnInit {
statusdata = [{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}];
value = statusdata[0];
....
这应该默认为选择的第一个选项。然后,如果您只想打印该值:
console.log(this.value.id);
console.log(this.value.name);
答案 1 :(得分:0)
要获得预期的结果,请在component.html和commponent.ts中使用以下使用Formbuilder,FormGroup和Form Control名称的选项
component.html
[formGroup]="profileForm"
formControlName="name"
`component.ts
3.声明表单组并使用formbuilder初始化名称
profileForm: FormGroup
constructor(private formBuilder: FormBuilder) {
this.profileForm = this.formBuilder.group({
name: new FormControl(1)
});
4。在按钮上,单击使用this.profileForm.get('name').value
register(){
console.log('selected Value', this.profileForm.get('name').value);
console.log('selected name', this.statusdata.filter(v => v.id == this.profileForm.get('name').value)[0].name);
}
供参考的示例工作代码-https://stackblitz.com/edit/angular-unnal4?file=src/app/app.component.ts
请参阅此链接以获取有关反应式的更多详细信息-https://angular.io/guide/reactive-forms