我正在使用 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/