Angular Custom Form Control-对带有selectionChange事件的mat-select进行更改检测

时间:2019-02-20 12:40:25

标签: angular angular-material angular7

我具有带有mat-select的自定义表单控件

我正在尝试侦听父组件中的更改事件

但是我的onTouchedCallback由于某些原因无法正常工作

我做错了什么?

预先感谢❤

这是我的“自定义”表单控件:

import { Component, OnInit, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

const noop = () => { };

export interface Food {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'app-custom-select-form-control',
  templateUrl: './custom-select-form-control.component.html',
  styleUrls: ['./custom-select-form-control.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: forwardRef(() => CustomSelectFormControlComponent),
    },
  ]
})
export class CustomSelectFormControlComponent implements OnInit, ControlValueAccessor {
  foods: Food[] = [
    { value: 'steak-0', viewValue: 'Steak' },
    { value: 'pizza-1', viewValue: 'Pizza' },
    { value: 'tacos-2', viewValue: 'Tacos' }
  ];
  constructor() { }

  ngOnInit() {
  }


  selectedOption: String;
  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: any) => void = noop;
  propagateChange = (_: any) => { };


  writeValue(val: string): void {
    this.selectedOption = val;
  }
  registerOnChange(fn: any): void {
    this.onChangeCallback = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouchedCallback = fn;
  }

  get value(): String {
    return this.selectedOption;
  }

  set value(v: String) {
    if (v != undefined && v != null && v !== this.selectedOption) {
      this.selectedOption = v;

    }
  }


  selectionChange(e:any)
  {
    this.value = e.value;
    this.onChangeCallback(this.value);
  }

}

这是我的html文件:

  <mat-form-field>
  <mat-select placeholder="Favorite food"  (selectionChange)='selectionChange($event)'>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

这是我的父组件HTML:

<app-custom-select-form-control 
     (change)='customControlChangeDetection($event)'>
</app-custom-select-form-control>

调试器在 selectionChange 中停止,但未在父控制器中达到 selectionChange

如果我用简单的输入/ mat-input代替mat-select,那么一切正常。

我也尝试过使用mat-date-picker,并且那里的变化检测效果不佳

1 个答案:

答案 0 :(得分:0)

将您的父组件写成这样,

<app-matchild (changeEvent)="parentMethod()"></app-matchild>

在ts组件文件中这样写,

  parentMethod() {
    console.log('Parent Method executed');
  }

您的子组件是这样的,

<mat-form-field>
  <mat-select
    placeholder="Favorite food"
    (selectionChange)="selectionChange($event)"
  >
    <mat-option *ngFor="let food of ['food1', 'food2', 'food3']" [value]="food">
      {{ food }}
    </mat-option>
  </mat-select>
</mat-form-field>

在子组件ts文件中定义这样的方法,

selectionChange(evt) {
    debugger;
    this.changeEvent.emit();
  }