【问题标题】:onChange event does not fire with FormControl and ControlValueAccessor (angular 6)onChange 事件不会与 FormControl 和 ControlValueAccessor 一起触发(角度 6)
【发布时间】:2018-09-18 09:55:23
【问题描述】:

我正在尝试用自定义组件包装 ng-select (https://github.com/ng-select/ng-select) 组件,我正在使用具有反应形式的 ControlValueAccessor,

export class ShNgSelectComponent implements OnInit, OnChanges, 
ControlValueAccessor {
   @Input() shItems: Array<object>;
   @Input() shBindValue: string;
   @Input() shBindLabel: string;
   @Input() shPlaceholder: any;

  @Output() shChange = new EventEmitter<Object>();

  ngOnInit() {  
  }


  writeValue(value: any): void {
    this.shItems = value || '';
  }

  propagateChange(event){
    this.shChange.emit(event);
   }


  registerOnChange(fn) {
    this.propagateChange = fn;
   }

  registerOnTouched() { }
}

这里是 sh-ng-select 的模板

<ng-select [items]='shItems' [bindValue]='shBindValue' [placeholder]='shPlaceholder' [bindLabel]='shBindLabel' (change)='propagateChange($event)'></ng-select>

这是我要嵌入自定义组件的主要组件

<sh-ng-select [shItems]='manufactureList' [shFormGroup]='requestForm' (shChange)='getModels($event)' formControlName="manufactureId" [shPlaceholder]='"اختر الشركة المصنعة"' [shBindValue]='"id"' [shBindLabel]='"name"'></sh-ng-select>

在我添加 formControlName 之前,shChange 事件正常触发,但是一旦我这样做,事件就不会触发,并且控制台不会抛出任何错误......这是为什么呢?

【问题讨论】:

    标签: angular form-control angular-ngselect


    【解决方案1】:

    对我来说,当您添加 formControlName 时,它​​会绑定它需要工作的所有内容,因此它将调用 registerOnChange 、 registerOnTouched、writeValue... 因为他调用 registerOnChange 并执行“this.propagateChange = fn" propageChange 方法将不再引用您定义的方法:

      propagateChange(event){
        this.shChange.emit(event);
       }
    

    因此不再调用 shChange 事件发射器


    有关更多信息,使组件使用 [(ngModel)] / formControlName 重复相同的模式,在这里您可以找到一个简单的实现,您可以扩展它以在您的组件中使用: https://github.com/xrobert35/asi-ngtools/blob/master/src/components/common/default-control-value-accessor.ts

    一个使用它的简单组件:https://github.com/xrobert35/asi-ngtools/blob/master/src/components/asi-checkbox/asi-checkbox.component.ts

    【讨论】:

    • 它在完成上述实现后工作,除了它抛出一个错误:“ERROR TypeError: items.map is not a function”,这是由于 shItems 传递给 ng- 中的 [items] select 被转换成一个字符串并且 [items] 接受一个数组
    • 当 formControl 初始化时,它将使用默认值调用 writeValue。这里我认为默认值是未定义的所以 this.shItems = value || '';将 "this.shItems 定义为 '' ,你应该写:this.shItems = value || [];
    • 删除 this.shItems = value || 后它起作用了'';来自 writeValue() 方法
    • 你改写了什么?
    • 我把它留空了!
    猜你喜欢
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2016-12-04
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多