javascript 如何在ControlValueAccessor中启动更改检测(valueChanges)

xzlaal3s  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(104)

我有一个formControl,我试图设置它的值,然后触发变化检测,这样其他组件中的valueChanges就可以得到我在这里设置的变化-但它不起作用。true。不触发valueChanges

<mat-select [formControl]="myCtrl" (selectionChange)="changed($event.value)">
      <mat-option ... >{{ ... }}</mat-option>
    </mat-select>
providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => MyComponent),
      multi: true,
    },
  ],
...
  public selectedValue: number;
  public changed: (value: number) => void;
  public touched: () => void;
  public isDisabled: boolean;

  writeValue(value: any): void {
    this.selectedValue = value;
  }
  registerOnChange(fn: any): void {
    this.changed = fn;
  }
  registerOnTouched(fn: any): void {
    this.touched = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    this.isDisabled = isDisabled;
  ...

  myCtrl = = new FormControl();
  ...
  ngOnInit(): void {

    this.subject$.subscribe((data) => {
      this.data = data
      if (data) {
        //this line below doesn't seem to kick off change detection
        this.myCtrl.setValue(1, { emitEvent: true })
        
        /*I also tried forcing change detection with the this.changed method but got an 
          error like  ERROR TypeError: this.changed is not a function*/ 
        //this.changed(1)
      }
    }
    )
  }
kzipqqlq

kzipqqlq1#

我猜你没有得到它的权利。你只需要做一个函数和selectionChange()调用。像在你的情况下,做一个名为changed的函数。尝试控制整个事件,并检查是否值显示在对象中,如果它这样做。你可以使用该值在任何地方,你需要。即传递到一个变量或观察者

相关问题