代码之家  ›  专栏  ›  技术社区  ›  Aeseir

以编程方式移除“选择”(Angular6材质)上的焦点/模糊

  •  3
  • Aeseir  · 技术社区  · 7 年前

    我复制了角6材料自动完成的简单示例: Simple Autocomplete

    我正试图弄清楚在选择之后如何移除焦点。

    我添加了以下更改:

    以HTML格式

    <mat-autocomplete #autoGroup="matAutocomplete" (optionSelected)="onSelectionChanged($event)">
    

    在组件中

      onSelectionChanged(event: MatAutocompleteSelectedEvent) {
        console.log(event.option.value);
      }
    

    在它将值输出到控制台之后,我想从输入字段中除去焦点,但不确定如何做到这一点。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Aeseir    7 年前

    mat-focused

    export class AutocompleteSimpleExample {
      myControl: FormControl = new FormControl();
      public matForm ;
      constructor(){
    
      }
    
      ngOnInit(){
        this.matForm =  document.getElementById("matForm") 
      }
      options = [
        'One',
        'Two',
        'Three'
       ];
    
      test(option){
        console.log(option)
        setTimeout(function(){
          this.matForm.classList.remove('mat-focused' )}, 100);
      }
    }
    

    <form class="example-form">
      <mat-form-field class="example-full-width test" #matForm id="matForm">
        <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" #textInput>
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="test($event.option)">
          <mat-option *ngFor="let option of options" [value]="option">
            {{ option }}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </form>
    

    stackblitz

    export class WhateverComponent {
    @ViewChild('textInput') textInput: ElementRef;
    //all other code
    }
    

    onSelectionChanged(event: MatAutocompleteSelectedEvent) {
        console.log(event.option.value);
        // blur will remove focus on the currently selected element
        this.matInputMain.nativeElement.blur();
        // if you using form you can wipe the input too
        this.yourForm.reset();        
      }
    

        2
  •  2
  •   Andrea Dompè    6 年前

    <input #autoCompleteInput type="text" [matAutocomplete]="auto"/>
    

    @ViewChild('autoCompleteInput', { read: MatAutocompleteTrigger }) autoComplete: MatAutocompleteTrigger;
    
      close() {
        this.autoComplete.closePanel();
      }
    

    Plunker

    推荐文章