简体   繁体   中英

How to start change detection (valueChanges) inside a ControlValueAccessor

I have a formControl which I'm trying to setValue and then trigger change detection so valueChanges in my other components would get the change i'm setting here- but it's not working. Even if i put emitEvent: true. Doesn't trigger 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)
      }
    }
    )
  }

I guess you are not getting it right. you just need to make a function and on selectionChange() call that. like in your case make a function named changed . try to console the whole event and check if value shows in the object if it does. you can use that value anywhere you need to.ie pass to a variable or an observer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM