表单 – 防止Angular 2在编辑输入字段时应用更改

我使用插值将变量绑定到输入字段(变量的值在输入字段中反映).只要数据库中的相应值发生更改,变量就会在后台自动更新.

我想阻止Angular将变量的更改应用于用户当前正在编辑此字段的输入字段.否则,将覆盖用户的编辑.

(换句话说:我希望Angular在更新值之前检查输入字段当前是否使用ng-pristine标记而不是ng-dirty.)

实现这一目标最容易的原因是什么?

理念:
是不是可以实现一个等于ngModel的指令,但检查在应用该值之前是否设置了类ng-dirty?

最优方案:
有一个指令,它执行双向数据绑定,如ngModel.如果未为视图设置“ng-dirty”标志,则该指令将模型中的更改应用于视图.如果视图失去焦点(如果模糊事件被触发),该指令将视图中的更改应用于模型.

最佳答案 我可以看到这样做的一种方法是创建一个注入NgModel的指令.您可以使用它来写入视图(在本例中为输入),并根据需要写入模型.您还可以检查模型是否是原始的而不是脏的.例如

import { Directive, OnInit, OnDestroy, Self } from '@angular/core';
import { NgModel } from '@angular/forms';

@Directive({
  selector: '[updateInput][ngModel]'
})
export class UpdateDirective implements OnInit, OnDestroy {
  private interval: any;

  constructor(@Self() private model: NgModel) {}

  ngOnInit() {
    let counter = 0;
    this.interval = setInterval(() => {
      console.log(`pristine: ${this.model.pristine}, dirty: ${this.model.dirty}`);
      if (this.model.pristine && !this.model.dirty) {
        counter += 2;
        this.model.valueAccessor.writeValue(`It's been ${counter} seconds...`);
        // the model will not be initially updated until the first editing by the user.
        // If you want the model updated when you write to the input, call the following.
        // Or comment it out if you don't want this behavior.
        this.model.viewToModelUpdate(`It's been ${counter} seconds...`);
      } else {
        clearInterval(this.interval);
      }
    }, 2000);
  }

  ngOnDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }
}

《表单 – 防止Angular 2在编辑输入字段时应用更改》

这是Plunker.

注意:此指令的选择器不是很好.这只是一个POC.如果您想要一个更准确的选择器来处理所有用例,您可能需要查看用于DefaultControlValueAccessor的选择器

点赞