【问题标题】:how can I have custom two way databinding make a form dirty我怎样才能有自定义的两种方式数据绑定使表单变脏
【发布时间】:2018-04-12 12:42:26
【问题描述】:

我创建了一个具有双向数据绑定的组件

class MyCustom2Way{
      @Input() text: string;
      @Output() textChange = new EventEmitter<string>();
      // MyCustom2Way has something in the template that will 
      // trigger testChange.emit when user interacts with it
}

现在假设我以这样的形式使用MyCustom2Way

<form action="" #myForm="ngForm">
  <my-custom-2-way [(text)]="model.field" name="field"></my-custom-2-way>
</form>

当用户使用MyCustom2Way 进行迭代时,我如何让MyCustom2Way 变成myForm 脏?

【问题讨论】:

    标签: javascript angular data-binding


    【解决方案1】:

    您可以像这样将表单传递给 my-custom-2-way 组件

    <my-custom-2-way [(text)]="model.field" name="field" [form]="myForm"></my-custom-2-way>
    

    然后在我的自定义组件中

    class MyCustom2Way{
          @Input() text: string;
          @Output() textChange = new EventEmitter<string>();
          // MyCustom2Way has something in the template that will 
          // trigger testChange.emit when user interacts with it
          @Input Form:any 
          this.form._pristine=true;
    }
    

    【讨论】:

      【解决方案2】:

      你应该使用ngModel 和自定义ControlValueAccessor,否则表单对你的组件一无所知,所以它不会被标记为脏。 [(text)]="model.field" - 只是语法糖。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        • 1970-01-01
        • 2013-09-23
        • 1970-01-01
        相关资源
        最近更新 更多