我有两个分别称为hours
和minutes
的字段,它们正在串联并存储在一个名为duration
的变量中:
JSON 看起来像这样:
[
{
"displayName": "Car Rent",
"duration": "06:27:00",
},
{
"displayName": "Bike Rent",
"duration": "10:15:00",
},
{
"displayName": "Texi Rent",
"duration": "05:30:00",
},
]
组件代码:
HTML
<form [formGroup]="addForm">
<div>
<mat-form-field>
<input matInput placeholder="Hours" formControlName="hours" required>
</mat-form-field>
</div>
<div>
<mat-form-field>
<input matInput placeholder="Minutes" formControlName="minutes" required>
</mat-form-field>
</div>
<button mat-flat-button type="submit" (click)="onSubmit()">Save</button>
</form>
TS
import { Component } from '@angular/core';
import { ContactService } from './contacts.service';
import {
FormBuilder,
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public addForm: FormGroup;
public someWork;
constructor(private fb: FormBuilder,
private myService: ContactService) {}
ngOnInit() {
this.addForm = this.fb.group({
hours: [null],
minutes: [null],
});
}
public onSubmit(): void {
this.someWork = this.addForm.value;
this.someWork.duration =
`${this.addForm.value.hours}:${this.addForm.value.minutes}`;
console.log(this.someWork);
this.ContactService.addWorkers(this.someWork);
}
}
我想以另一种形式将duration
显示为hours
和minutes
来编辑duration
。我如何通过 api 伪装在单独的字段中显示hours
和minutes
。
像这样:
答案 0 :(得分:1)
您可以从JSON拆分字符串。一个例子:
const durationArray = duration.split(':'); // Will return an array
// durationArray[0] = hours, durationArray[1] = minutes
this.addForm.value.hours = durationArray[0];
this.addForm.value.minutes = durationArray[1];