为什么ngModel写入值两次

时间:2017-09-05 07:05:56

标签: angular

我编写了一个实现ControlValueAccessor接口的自定义表单控件。

@Component({
  selector: 'counter',
  template: `
    <button (click)="increase($event)">+</button>
    {{counter}}
    <button (click)="decrease($event)">-</button>
  `,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CounterComponent),
    multi: true
  }]
})
export class CounterComponent implements OnInit, ControlValueAccessor {
  private counter: number = 0;
  private onChange: (_: any) => void;
  private onTouched: () => void;

  ngOnInit() { }

  writeValue(value) {
    console.log('Write value', value);
    this.counter = value;
  }

  registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }

  registerOnTouched(fn: () => void): void { this.onTouched = fn; }

  increase() {
    this.counter++;
    this.onChange(this.counter);
  }
  decrease() {
    this.counter--;
    this.onChange(this.counter);
  }
}

但是当我使用ngModel时,我发现writeValue会触发两次。

@Component({
  selector: 'my-app',
  template: '<counter [(ngModel)]="count"></counter>',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  count = 5;
}

output:

Write value null
Write value 5

在线示例链接:https://stackblitz.com/edit/angular-ngmodel-write-value

1 个答案:

答案 0 :(得分:1)

这是角项目中的一个开放缺陷 - https://github.com/angular/angular/issues/14988