我尝试将带有角度2的表单发送到rest api,我的问题是我想给select标签命名一个标签值。
示例:
这是component.html:
<div class="ui raised segment">
<h2 class="ui header">Demo Form: Sku</h2>
<form #f="ngForm"
(ngSubmit)="onSubmit(f.value)"
class="ui form">
<div class="field">
<label for="skuInput">SKU</label>
<input type="text"
id="skuInput"
placeholder="SKU"
name="sku" ngModel>
</div>
<div class="field">
<label for="select1" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:spanish: </label>
<select class="form-control" name="note1" id="select1" ngModel>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<label for="select2" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">english: </label>
<select class="form-control" name="note2" id="select2" ngModel>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<label for="select3" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:frensh: </label>
<select class="form-control" name="note3" id="select3" ngModel>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<button type="submit" class="ui button">Submit</button>
</form>
</div>
我希望选择1 的名称为西班牙语(标签1的值)
component.ts:
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-post-history',
templateUrl: './post-history.component.html',
styleUrls: ['./post-history.component.css']
})
export class PostHistoryComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
onSubmit(form: any): void {
console.log('you submitted value:', form);
}
}
如果我给每个选择标签添加不同的名称,那么每件事都可以正常工作:
每个选择都有名称,而不是我想要显示每个选择的标签值。
答案 0 :(得分:1)
LABELs are not form elements that can hold or send data. They are captions tied to form elements.
因此,标签不会随着提交的ngForm一起发送。
为什么不将标签值作为选择控件的名称:
<label for="select1" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:spanish: </label>
<select class="form-control" name="spanish" id="select1" ngModel>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
像这样你会得到你想要的结果:
** 要解决您的注释,您始终可以将标签文本保留在组件中的数组中,如:
labelsName = [{select1: "your 15 words label"}, {select2: "another label"}]
然后,当您收到提交时,将每个选择器的名称与数组上的键映射以获取标签。