Angular2 select default first option

前端 未结 10 1551
半阙折子戏
半阙折子戏 2021-01-04 08:32

How do i select the first option in a select by default in angular 2 the following code don\'t seems to work.


                        
    
提交评论

  • 2021-01-04 09:07

    try using this

    <select id="sType" class="form-control" [(ngModel)]="params.searchType" (ngModelChange)="onChange($event)"> 
         <option *ngFor="let t of sTypes" [Value]="t.value">{{t.name}}</option> 
    </select>
    

    in controller/component use-

    this.params.searchType=sTypes[0]
    
    onChange(updatedValue) {
    this.params.searchType = updatedValue;
    //other code
    }
    
    0 讨论(0)
  • 2021-01-04 09:10

    Reactive form controls

    You can also set value in component using rform.controls

    this.rForm.controls['id'].setValue(this.array[0].id);
    
    0 讨论(0)
  • 2021-01-04 09:16

    You are mixing two things that cannot work together, as they conflict: ngModel and selected. If you bind with params.searchType you have to initialize params.searchType to the default value you want: this.params.searchType = sTypes[0];

    0 讨论(0)
  • 2021-01-04 09:23

    One more solution is the custom directive, which will listen to <option>s list changes and select the first item if none selected.

    import { AfterViewInit, Directive, ElementRef, Renderer2 } from '@angular/core';
    
    @Directive({
      selector: '[mySelectFirstOption]'
    })
    export class SelectFirstOptionDirective implements AfterViewInit {
      private observer: MutationObserver;
    
      constructor(
          private elementRef: ElementRef,
          private renderer: Renderer2) {
        if ((elementRef.nativeElement.tagName || '').toLowerCase() !== 'select') {
          throw new Error('mySelectFirstOption directive can only be applied to <select> elements');
        }
      }
    
      ngAfterViewInit() {
        setTimeout(() => this.trySelectFirstOption(), 0);
        this.observer = new MutationObserver(mutations => this.trySelectFirstOption());
        const config: MutationObserverInit = { childList: true };
        this.observer.observe(this.elementRef.nativeElement, config);
      }
    
      private trySelectFirstOption() {
        const nativeElement = this.elementRef.nativeElement;
        if (nativeElement.options.length > 0 && nativeElement.selectedIndex === -1) {
          this.renderer.setProperty(nativeElement, 'value', nativeElement.options[0].value);
          nativeElement.dispatchEvent(new Event('change'));
        }
      }
    }
    

    And then you can use it with <select> element like this:

    <select ... mySelectFirstOption>
    
    0 讨论(0)
  • 2021-01-04 09:23
     <select class="form-control" [(ngModel)]="selectedCDM" >
        <option *ngFor="let cdm of CDMs;let i = index"  [ngValue]='cdm'>
                    {{cdm.Name}}
        </option>
     </select>
    

    CDMs is an array of objects, where an object has Id and Name as attribute. And selectedCDM is set to first element of CDMs array

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