显示拆分并在2个输入字段中显示字符串值

时间:2019-01-11 08:40:02

标签: angular typescript angular6

我有两个分别称为hoursminutes的字段,它们正在串联并存储在一个名为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显示为hoursminutes来编辑duration。我如何通过 api 伪装在单独的字段中显示hoursminutes。 像这样:

enter image description here

1 个答案:

答案 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];