【发布时间】:2019-11-25 03:09:10
【问题描述】:
我正在使用 Angular CLI 和 Angular Material 制作表单,用于将数据发布到服务器上的 API,我想问两个问题:
在选择列表中,如果用户选择“Full”,则滑块值将固定为最大 100%,如果用户选择“Optional”,则滑块值将正常(最小 10%,最大 100% )。
在选择列表中,如果用户选择“Full”,当他们按下提交时,它将向API发送“0”而不是标签“Full”,如果用户选择“Optional”,它将发送API 中的“1”不是标签“可选”。
我不知道如何实现上面的这些要求,这是我正在使用的代码:
Form.component.html
<form [formGroup]="createItemForm">
<fieldset>
<div class="row">
<div class="col-lg-6">
<mat-form-field>
<mat-select placeholder="Select" formControlName="modeTaker" id="modeTaker">
<mat-option *ngFor="let value of modeTakers" value="value">{{ value }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div class="col-lg-6">
<span>Percent share</span>
<mat-slider
thumbLabel
[displayWith]="formatLabel"
min="10"
max="100"></mat-slider>
</div>
</div>
</fieldset>
<button mat-raised-button type="submit" (click)="createItems()" class="btn btn-primary pull-right"
[disabled]="!createItemForm.valid">Create a new items</button>
</form>
Form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { ApiService, NotificationService } from '@app/core';
import { Router } from '@angular/router';
createItemForm: FormGroup;
isSubmitting = false;
modeTakers = ['Full', 'Optional'];
constructor(
private formBuilder: FormBuilder,
private apiService: ApiService,
private ns: NotificationService,
private router: Router
) {
this.createItemForm= this.formBuilder.group({
'sharedPercent': [''],
'modeTaker': ['']
});
}
formatLabel(value: number) {
if (value <= 100) {
return Math.round(value) + '%';
}
return value;
}
createItems() {
const item = Object.assign({}, this.createItemForm.value);
this.isSubmitting = true;
this.apiService.post('/itemslist/', item )
.subscribe(({ name, id }) => {
this.ns.showNotification(`New ${name} created`);
this.router.navigate(['/itemslist', id]);
},
(error) => {
this.ns.errorNotification(error);
});
}
【问题讨论】:
-
那是什么问题?
-
其实没什么问题,就是2个需求不知道怎么解决
-
对于第二个 - 您可以通过添加
[{text:"Full", value:"0"},{text:"Optional", value:"1"}]来修改modeTakers列表 -
谢谢,有什么方法可以让滑块在应用新值后做出反应?
标签: angular typescript angular-material http-post