Angular2 choose the first option by default

How to choose the first option in the default selection in angular 2, the following code does not seem to work.

<select id="sType" class="form-control" [(ngModel)]="params.searchType"> <option *ngFor="let t of sTypes" [ngValue]="t.value" [attr.selected]="$index == 0 ? true : null">{{t.name}}</option> </select> 
+5
source share
8 answers

You can select the first option by default using the index value.

 <select id="sType" class="form-control" [(ngModel)]="params.searchType"> <option *ngFor="let t of sTypes; let i = index" [attr.value]="t.value" [attr.selected]="i == 0 ? true : null">{{t.name}}</option> </select> 
+4
source

Reactive Form Elements

You can also set the value in the component using rform.controls

 this.rForm.controls['id'].setValue(this.array[0].id); 
+3
source

try using

 <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 the use of the controller / component -

 this.params.searchType=sTypes[0] onChange(updatedValue) { this.params.searchType = updatedValue; //other code } 
+2
source

This works for angular 4.1.3:

 <option *ngFor="let t of sTypes; let i = index" [value]="t.value" [selected]="i==0"> 
+2
source

Another solution is a custom directive that will listen for changes to the <option> list and select the first element if none are 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 the <select> element as follows:

 <select ... mySelectFirstOption> 
+1
source

If you use Model Driven Forms, you can set the selected default value of your <select> in your component ( ngOnInit() )

componenet.file.ts

 public fieldSelect : any; ngOnInit(){ ... this.fieldSelect= { key: "mySelect", label: "Example Select"}; this.controlsConfig= []; this.controlsConfig[this.fieldSelect.key] = [""]; this.myFormGroup= this.formBuilder.group(this.controlsConfig); ... } 

component.file.html

 <div class="col-md-2" [formGroup]="myFormGroup"> <select (change)="onChangeTypeImp($event)" [formControlName]="fieldSelect.key"> <option *ngFor="let item of items;" [value]="item">{{item}}</option> </select> </div> 

Forms driven by models. Although using directives in our templates gives us the power of rapid prototyping without having too much of a template, we are limited by what we can do. Reactive forms, on the other hand, allow us to define our form using code and give us much greater flexibility and control over data validation. +

At first there is a bit of magic in its simplicity, but after you arrange the basics, you will learn that its building blocks will allow you to handle more complex use cases.

[example]

0
source
  <select class="form-control" [(ngModel)]="selectedCDM" > <option *ngFor="let cdm of CDMs;let i = index" [ngValue]='cdm'> {{cdm.Name}} </option> </select> 

CDM is an array of objects where the object has the Id and Name attribute. And selectedCDM is installed on the first element of the CDM array.

0
source

Or just like that :)

 <option *ngFor="let value of values; let i = index" [ngValue]="value" [attr.selected]="!i" >{{item}}</option> 

Enjoy it!

0
source

Source: https://habr.com/ru/post/1261179/


All Articles