如何使用反应形式的对象?

时间:2019-08-21 08:35:19

标签: javascript angular

我在反应形式中使用日期范围选择器。所以我使用的变量是一个对象。

{开始:时间戳,结束:时间戳,时区:字符串,最大:时间戳, 分钟:时间戳记}

当我在输入中显示它时,我得到:[Object-Object]

我想显示如下内容: {{date.start +'-'+ date.end}}

this.testDate = { start: 1565690444, end: 1565890444, min: 1265690441, max: 1640704921, timezone : "Asia/Dubai"};

TYPESCRIPT

this.configureForm = this.fb.group(<any>{
  test: [
    this.testDate,
    [
      Validators.required,
      UtilsValidator.periodFormat(DateFormatType.Default, this.testDate.timezone),
      UtilsValidator.dateMin(this.testDate.min, DateFormatType.Default, this.testDate.timezone),
      UtilsValidator.dateMax(this.testDate.max, DateFormatType.Default, this.testDate.timezone)
    ]
  ]});

HTML

<form [formGroup]="configureForm">
<ex-form-field>
      <input[formControlName]="'test'">
      <i [exDateTimePicker]  [exDateTimeFormControl]="getField('test')"> * </i>
    </ex-form-field>
</form>

你能帮我一下吗?

2 个答案:

答案 0 :(得分:0)

如果没有输入,则存在表单控件。这个想法是您的控件更改了formControl并显示其值,但是您无法编写简单的<input formControlName="test">

一个简单的例子,如果输入带有NgModel

<input [ngModel]="configureForm.get('test').value.start+ '-'+ configureForm.get('test').value.end"
       [ngModelOptions]="{standalone:true}"
       (ngModelChange)="change($event)"
  >

功能更改的地方可以像

change(value)
  {
    const values=value.split('-');
    if (values.length==2)
    {
      const control=this.configureForm.get('test');
      this.configureForm.get('test').setValue(
         {...control.value,start:+values[0],end:+values[1]},
         {emit:false})
    }
  }

请参阅stackblitz

答案 1 :(得分:-1)

哼。不幸的是,它没有起作用。我的验证器不会更新,并且当我通过在显示器上键入内容来编辑输入时也不会更新!

我尝试了这个示例(仅需一个(Validators.required)):

  <input
      [(ngModel)] = "dateTest"
      [ngModelOptions]="{standalone:true}"
      (change)="updateDate($event)" />

TypeScript:

    get dateTest() {
     if (!this.configureForm.get('test').value.start)
        return null;

   return this.configureForm.get('test').value.start + '-' + 
   this.configureForm.get('test').value.end;}



    updateDate(value: Event) {
     this.configureForm.controls['dateTest'].setValue({start: null, 
     end: null});}