Angular ControlValueAccessor 在(更改)事件中触发旧值

标签 angular angular6 controlvalueaccessor

我正在使用 Angular v6.0.0,我的组件实现了 ControlValueAccessor;
在更改事件中,我看到它始终是旧值,但是当绑定(bind) ngModel 的值时,它是新值。 我做了一个stackblitz example ;

 @HostListener('click')
  onToggle() {
    if (this.disabled) {
      return;
    }
    this.checked = !this.checked;
    this.change.emit(this.checked);
    this.changed(this.checked);
    this.touched(this.checked);
  }

  // Implement control value accessor

  changed = (_: any) => {};

  touched = (_: any) => {};

  public writeValue(obj: any) {
    if (obj !== this.checked) {
      this.checked = !!obj;
    }
  }

  public registerOnChange(fn: any) {
    this.changed = fn;
  }

  public registerOnTouched(fn: any) {
    this.touched = fn;
  }

最佳答案

当您使用EventEmmiter时,您必须在output事件中传递$event,因为$event保存发出的值

这是一个例子

<app-switch size="small" name="skip_notification" (change)="changed($event)" [(ngModel)]="value"></app-switch>

.ts

 changed(event) {
    this.value1 = event;
  }

此处已更新 Stackblitz

关于Angular ControlValueAccessor 在(更改)事件中触发旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997746/

相关文章:

具有动态值的 Angular index.html |网络 worker

Angular 2 本地主机和后端服务器连接

Angular Material DatePicker - 错误 : MdDatepicker: No provider found for DateAdapter

routes - Angular 6 带有延迟加载的子路由

Angular 6 元素 bool 输入参数

angular - 将 formControlName 传递给 Angular 组件

javascript - 当运行 Angular 8 生产 : Delete of an unqualified identifier in strict mode

Angular 6 : Cannot read property 'reset' of undefined

angular - 如何创建自定义响应式表单元素?

Angular 7 - ControlValueAccessor - 修剪绑定(bind)到表单的输入值