【问题标题】:Angular 5 - How to get the date pipe to correctly render in a dynamic form after the first form build?Angular 5 - 如何让日期管道在第一个表单构建后以动态表单正确呈现?
【发布时间】:2019-01-13 23:47:04
【问题描述】:

Angular 5.2.4 - 尽管有 reset(),但日期管道失败的反应形式

我正在创建一个动态生成的响应式表单。我的示例中有一个控件,它显示日期。日期应由日期管道(在模板中)格式化,并且在表单第一次构建时正确执行。但是,在连续的表单构建中,日期被呈现为日期字符串,而管道没有应用格式。

在每个表单构建中,我都会调用 FormGroup.reset(),并且还尝试将 FormGroup 设置为 null。

编辑:回答这个问题后,我将管道转换移到 .ts 文件中。这适用于许多情况,尽管在某些情况下它不适用于更复杂的生成形式。所以对很多人来说,这个解决方案会奏效。

我在下面包含了我的代码,并清楚地标记了我在收到答案后所做的更改。在这篇文章的底部还可以找到包含相同代码的 Stackblitz 链接。

这是我开始使用的 .ts 代码(我已经注意到我在 cmets 中的更改):

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
// ***added this DatePipe import after the answer***
import { DatePipe } from '@angular/common'; 

@Component({
  selector: 'material-app',
  templateUrl: 'app.component.html',
  styleUrls: ['./app.component.css'],
   // ***added following line after the answer***
  providers: [DatePipe]
})
export class AppComponent {
  formGroup: FormGroup;
  importantDate = "2018-08-22T12:34:56.789Z";
  anotherDate = "2015-11-00T01:23:45.678Z";
  test = 0;

 // *** added DatePipe injection to constructor after answer***
  constructor(private datePipe: DatePipe) { }

  ngOnInit() {
    this.buildForm(this.importantDate);
  }

 // ***added this function after the answer***
  transformDate(date) {
    return this.datePipe.transform(date, 'MM/dd/yyyy');
  }

  // build the form the first time
  buildForm(dateValue) {
    this.formGroup = new FormGroup({
      dateEnjoined: new FormControl(this.importantDate)
 /**NOTE: alternatively, "dateEnjoined: new FormControl(this.transformDate(dateValue))" would 
also work here. But the template pipe handles the first transformation OK.*/
    });
  }

// this is my original function to rebuild the form
  unSetAndRebuildForm_OLD_VERSION() {
    if (this.formGroup.get('dateEnjoined').value == this.anotherDate) {
      this.formGroup.reset({ dateEnjoined: this.importantDate });
      this.test = 0;
    } else {
      this.formGroup.reset({ dateEnjoined: this.anotherDate });
      this.test = 1;
    }
  }

// *** I altered the function to this version, after the answer***
  unSetAndRebuildForm() {
    if (this.test == 1) {
      this.formGroup.reset();
      this.formGroup.patchValue({ dateEnjoined: this.transformDate(this.importantDate) });
      this.test = 0;
    } else {
      this.formGroup.reset();
      this.formGroup.patchValue({ dateEnjoined: this.transformDate(this.anotherDate) });
      this.test = 1;
    }
  }
}

这是表单的 .html 代码(无需更改)。我已将日期管道留在表单中(到目前为止,这并没有中断,并且允许表单反映从服务器接收到的更新值,而不强制重新构建表单)。另外,请注意,我确实在“值”周围留下了括号 []:

<form class="basic-container" [formGroup]="formGroup">
  <input formControlName="dateEnjoined" 
  [value]="importantDate |  date: 'MM/dd/yyyy'">
  <button (click)="unSetAndRebuildForm()">  click me </button>
</form>

回答后,在我的AppModule.ts中,我还需要同时导入DatePipe并将其添加到providers数组中(在实际应用中,我在SharedModule中进行了这些更改):

import { DatePipe } from '@angular/common';

providers: [ DatePipe ]

https://stackblitz.com/edit/ang5-date-pipe-fails-after-first-build

【问题讨论】:

  • 我们无法查看源代码
  • 我们无法保存更改。所以修改后的代码变化没有反映。
  • @SureshKumarAriya 你能分叉和编辑吗?
  • 这里是更新的stackblitz代码stackblitz.com/edit/…
  • @Mayken 谢谢 - 我已根据您的评论进行了修改。

标签: angular angular2-forms


【解决方案1】:

我们也可以从组件端调用 datepipe。另外,我们需要导入 DatePipe 作为组件提供者

    import { DatePipe } from '@angular/common';

    @Component({
      selector: 'material-app',
      templateUrl: 'app.component.html',
      styleUrls: ['./app.component.css'],
      providers: [DatePipe]
    })

    transformDate(date) {
      return this.datePipe.transform(date, 'MM/dd/yyyy');
    }

    unSetAndRebuildForm() {
        if (this.formGroup.get('dateEnjoined').value == this.anotherDate) {
          this.formGroup.reset();
          // console.log(this.transformDate(this.importantDate));
          // alert(this.transformDate(this.importantDate));
          this.formGroup.patchValue({ dateEnjoined: this.transformDate(this.importantDate) });
          this.test = 0;
        } else {
          this.formGroup.reset();
          // console.log(this.transformDate(this.anotherDate));
          // alert(this.transformDate(this.anotherDate));
          this.formGroup.patchValue({ dateEnjoined: this.transformDate(this.anotherDate) });
          this.test = 1;
        }
      }

另外请从模板文件中删除 [value]。

【讨论】:

  • 我认为这将以我的动态形式工作。在 unsetAndRebuildForm() 中,如果将测试更改为if (this.test == 0),则可以无休止地重置表单。让我再测试一点,除非看不见,否则将标记为正确答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
相关资源
最近更新 更多