繁体   English   中英

Angular 2 反应式表单 - 从 formControlName 管道传递一个值

[英]Angular 2 reactive forms - piping a value from a formControlName

使用 Angular 2,我有一个名为“example”的参数,它是一个 Date 对象。 在模板中,我想用日期管道格式化“示例”。 像这样的东西:

<input type="text" [value]="example | date:'shortTime'">
// 9:00 AM 

但是,我需要使用 Angular 的反应形式。 FormControls 优先,因此formControlName将覆盖value指令中的任何内容。

<input type="text" formControlName="example">
// Wed Mar 08 2017 09:00:00 GMT-0700 (MST)

<input type="text" formControlName="example" [value]="example | date:'shortTime'">
// Wed Mar 08 2017 09:00:00 GMT-0700 (MST)

formControlName指令不接受管道。 如何在响应式表单的模板中格式化 Date 对象?

伪代码:

@Component({
    template: `
        <form [formGroup]="formGroup">
            Example: <input type="text" formControlName="example">
        </form>
    `
})

export class ExampleComponent implements OnInit {
    public formGroup: FormGroup;
    public example: Date = new Date();

    public ngOnInit() {
        this.formGroup = new FormGroup({
            example: new FormControl(this.example)
        });
    }
}

更新:我意识到一种更简单、更明智的方法是使用 valueChanges 对 change 事件值执行带有管道转换的 setValue。

如果您有许多带有订阅的表单控件,可能有一些关于清理订阅和提高效率的最佳实践。 您还可以在处理/提交最终表单值时清除任何不需要的管道转换。

基本示例(另请参见:原始来源):

ngOnInit() {
  this.searchField = new FormControl();
  this.searchField.valueChanges
      .subscribe(val => {
        this.searchField.setValue(myPipe.transform(val))
      });
}

带有去抖动延迟 + 清晰度检查的摘录(由RxJS pipeable operators 提供):

this.searchField.valueChanges
    .pipe( // RxJS pipe composing delay + distinctness filters
        debounceTime(400),
        distinctUntilChanged()
    )
    .subscribe(term => {
      this.searchField.setValue(myPipe.transform(val))
  });

原建议...

此答案描述了如何为输入字段创建自定义控件值访问器,该输入字段在 onChange(获取 convertTo* 自定义函数)和 writeValue(获取 convertFrom 自定义函数)方法中插入自定义时间戳转换函数。

您可能会创建类似的东西(例如,将模板等调整为其他表单输入类型),但将转换函数替换为您想要的管道转换方法(可能是两种不同的类型)以实现您所追求的目标。 Angular 文档或源代码可能有助于了解更多细节。

我认为其他建议的方法在初始表单控件创建期间涉及管道转换,它们更受限制并且可能不是您所期望的,因为当用户更改输入值时,它不会继续应用这些更改。 一开始它会正确显示,但任何操作都会失去转换过滤,并且表单将简单地按原样提交,而不应用管道转换。

我可能遗漏了一些关于其他建议的工作方式或特别是您所追求的内容。

为什么不直接格式化日期? 喜欢:

this.formGroup = new FormGroup({
        example: [new Date().toISOString()]
    });

这里我们可以依靠JS。 你想使用shortTime作为你的管道,所以输出可能是......

10:50 PM

因此,当您分配日期值时,请使用以下命令:

this.formGroup = new FormGroup({
  example: new FormControl(new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}))
});

......你会按照你的意愿显示时间:)

如果您有兴趣,请阅读有关Date.prototype.toLocaleTimeString()的进一步阅读!

我认为你可以使用它来显示格式化的日期

<input type="text" [value]="formGroup.get('example').value | date:'MM/dd/yyyy'">

月/日/年 - 1/1/1111

date:'MM/dd/yyyy' output: 17/09/2019
or
date:'shortDate' output: 17/9/19

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM