如何为 mat select 创建自定义指令并监听 change 事件

how to create a custom directive for mat select and listen to the change event

在我的项目中,由于一些只读错误,必须使用 ElementRef 的 nativeelement.value。 只有我的指令

export class DeliveryAcrossDirective {
  @Input('key') key: string;
  @Input('component') component: string;
  constructor(
    private store: Store,
    private elementRef: ElementRef<HTMLInputElement>
  ) {
    this.key = '';
    this.component = '';
  }
  @HostListener('change') onChange() {
    console.log('noticed something');

    this.store.dispatch<IAction<IAdjust>>({
        type: RDX_DELIVERY_ACROSS_ADJUST,
        payload: {
          key: this.key,
          value: this.elementRef.nativeElement.value
        },
        component: this.component
      })
  }

}

没有从我的垫子上捕获更改事件select

<mat-form-field class="full-width" [@transformRightLeftStateTrigger]="stateDown | async">
  <mat-label>
    {{ country | async }}
  </mat-label>
  <mat-select [formControl]="countryFormControl"
  appDeliveryAcross
  [key]="'iso'"
  [component]="'delivery-across'" >
    <mat-option *ngFor="let language of (languages | async)"  [value]="language.value">
      {{ language.country }}
    </mat-option>
  </mat-select>
</mat-form-field>

而经典输入

        <mat-form-field class="full-width" [@transformRightLeftStateTrigger]="stateDown | async">
          <input matInput
          [formControl]="minFormControl"
          [errorStateMatcher]="errorStateMatcher"
          placeholder="Minimaal"
          appDeliveryAcross
          [key]="'min'"
          [component]="'delivery-across'"
          type="number">
        </mat-form-field>

有人知道如何使用指令从垫子 select 捕获更改事件吗?

我不确定您使用的是哪个版本的 Angular Material,但可能 change mat-select [=14= 不存在简单事件]

您似乎已经修改了 mat-selects

的指令

要检测 mat-select 的变化,您不需要 HostListener,只需订阅 MatSelect

selectionChange
export class DeliveryAcrossDirective implements OnInit, OnDestroy {
  selectionSub: Subscription;

  constructor(
    private host: MatSelect
  ) {
  }

  ngOnInit(): void {
    this.selectionSub = this.host.selectionChange.subscribe(option => {
      console.log(option);
      // Do something
    });
  }

  ngOnDestroy(): void {
    this.selectionSub?.unsubscribe();
  }
}