【问题标题】:how to create a custom directive for mat select and listen to the change event如何为 mat select 创建自定义指令并监听 change 事件
【发布时间】:2021-11-02 14:32:08
【问题描述】:

在我的项目中,必须使用 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
      })
  }

}

没有从我的垫子选择中捕获更改事件

<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>

有谁知道如何使用指令从 mat select 中捕获更改事件?

【问题讨论】:

    标签: angular typescript angular-directive mat-select


    【解决方案1】:

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

    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();
      }
    }
    

    【讨论】:

      【解决方案2】:

      我不确定您使用的是哪个版本的 Angular Material,但对于 mat-select https://stackoverflow.com/a/50223943/9602452 可能不存在 change 事件简单

      好像你已经修改了mat-selects 的指令

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-22
        • 2017-05-11
        • 2011-08-09
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 2012-01-22
        相关资源
        最近更新 更多