Angular Material Autocomplete force selection

后端 未结 6 1548
情书的邮戳
情书的邮戳 2021-02-07 09:18

In my angular 5 application I have some matAutocomplete, but I want to force the selection of oone of suggestions, so I am following this approach: stackblitz but for some reas

6条回答
  •  半阙折子戏
    2021-02-07 10:16

    The example they give on the site uses Reactive Form approach, but in your case you seem to lean toward Template Driven Approach, but you're not using a form period.

    So you could directly access the dom element like you're doing now.

    Create a local reference to your input, maybe call it autoComplInput

    Inside your component file, you'll want to import ElementRef and View Child

    import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
    

    Inside your component, import ViewChild, and declare it an ElementRef type

    @ViewChild('autoComplInput') autoComplInput: ElementRef;
    

    Then at some point of initialization, just assign referenced element value

      ngOnInit() {
        this.autoComplInput.nativeElement.value = this.countries[0];
      }
    

    Demo based on Angular Material 2's example, since you didn't provide all the information needed.

    In your html

    
      
      
        
          
    {{country}}

    In your component

    import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
    
    @Component({
      selector: '<...>',
      templateUrl: '<...>',
      styleUrls: ['<...>'],
    })
    export class <...> implements OnInit  {
    
      @ViewChild('autoComplInput') autoComplInput: ElementRef;
    
      countries = [
        'Alabama',
        'Alaska',
        'Arizona',
        'Arkansas',
        'California',
        'Colorado',
        'Connecticut',
        'Delaware',
        'Florida',
        'Georgia',
        'Hawaii',
        'Idaho',
        'Illinois',
        'Indiana',
        'Iowa',
        'Kansas',
        'Kentucky',
        'Louisiana',
        'Maine',
        'Maryland',
        'Massachusetts',
        'Michigan',
        'Minnesota',
        'Mississippi',
        'Missouri',
        'Montana',
        'Nebraska',
        'Nevada',
        'New Hampshire',
        'New Jersey',
        'New Mexico',
        'New York',
        'North Carolina',
        'North Dakota',
        'Ohio',
        'Oklahoma',
        'Oregon',
        'Pennsylvania',
        'Rhode Island',
        'South Carolina',
        'South Dakota',
        'Tennessee',
        'Texas',
        'Utah',
        'Vermont',
        'Virginia',
        'Washington',
        'West Virginia',
        'Wisconsin',
        'Wyoming',
      ];
      constructor( ) {}
    
      ngOnInit() {
        this.autoComplInput.nativeElement.value = this.countries[0];
      }
    
    
    }
    

提交回复
热议问题