How to make tab key as enter key in Angular Material?

后端 未结 1 448
天涯浪人
天涯浪人 2021-01-03 11:50

this is my angular materiel auto complete code



        
1条回答
  •  隐瞒了意图╮
    2021-01-03 12:22

    Improve my comment, and based on the response we can create a directive

    import { Directive, AfterViewInit, OnDestroy, Optional } from '@angular/core';
    import { MatAutocompleteTrigger } from '@angular/material';
    
    
    @Directive({ selector: '[tab-directive]' })
    export class TabDirective implements AfterViewInit, OnDestroy {
      observable: any;
      constructor(@Optional() private autoTrigger: MatAutocompleteTrigger) { }
      ngAfterViewInit() {
        this.observable = this.autoTrigger.panelClosingActions.subscribe(x => {
          if (this.autoTrigger.activeOption) {
            this.autoTrigger.writeValue(this.autoTrigger.activeOption.value)
          }
        })
      }
      ngOnDestroy() {
        this.observable.unsubscribe();
      }
    }
    

    You use:

    
    

    (see stackblitz)

    Update We can control only tab.key, else always you close, you get the selected value, so

    @Directive({ selector: '[tab-directive]' })
    export class TabDirective{
      observable: any;
      constructor(@Optional() private autoTrigger: MatAutocompleteTrigger) { }
    
      @HostListener('keydown.tab', ['$event.target'])onBlur()
      {
        if (this.autoTrigger.activeOption) {
            this.autoTrigger.writeValue(this.autoTrigger.activeOption.value)
          }
      }
    
    }
    

    (see a new stackblitz)

    Update 2 I don't believe this answer has so many upvotes because it's wrong. As @Andrew allen comments, the directive not update the control. Well, It's late, but I try to solve. One Option is use

    this.autoTrigger._onChange(this.autoTrigger.activeOption.value)
    

    Anohter idea is inject the ngControl, so

      constructor(@Optional() private autoTrigger: MatAutocompleteTrigger,
                  @Optional() private control:NgControl) { }
      ngAfterViewInit() {
        this.observable = this.autoTrigger.panelClosingActions.subscribe(x => {
          if (this.autoTrigger.activeOption) {
            const value=this.autoTrigger.activeOption.value;
            if (this.control)
              this.control.control.setValue(value,{emit:false});
            this.autoTrigger.writeValue(value);
          }
        })
      }
    

    0 讨论(0)
提交回复
热议问题