Deepak
Deepak

Reputation: 1068

ngModel on select not showing initial, default value

I have following Angular code:

comp.html

<select [(ngModel)]="selectedBanner" (change)="onBannerChange()">
                    <option *ngFor="let banner of banners" 
                    [ngValue]="banner">{{banner.BannerDesc}}</option>

                </select>

comp.ts

    public banners: any[] = [
        {BannerId: 1, BannerDesc: 'AAAA'},
        {BannerId: 2, BannerDesc: 'BBBB'},
        {BannerId: 3, BannerDesc: 'CCCC'},
        {BannerId: 4, BannerDesc: 'DDDD'},
    ];
    public selectedBanner: any = {BannerId: 3, BannerDesc: 'CCCC'};
    onBannerChange() {
        console.log(this.selectedBanner);
    }

However, on load, the select dropdown is always blank. Only when I change, it gets the value. How can I set the default value on load?

I am using angular 4.0.0

Upvotes: 2

Views: 5554

Answers (4)

Ramsha Ahsan
Ramsha Ahsan

Reputation: 21

It is also important that initial value which you're assinging to ngModel variable should be a number. If it is not a number then use parseInt(value);

Upvotes: 0

AVJT82
AVJT82

Reputation: 73377

Fine answers here, but just to throw in this as we found out that this selectedBanner would be a global variable. You can do it like jLee suggested, also you can simply use find(), where you would assign (create reference) the value from the array based on your object, so:

ngOnInit() {
  this.selectedBanner = this.banners.find(x => 
       x.BannerId == this.selectedBanner.BannerId)
}

Upvotes: 1

jLee
jLee

Reputation: 483

The issue you are going to face when trying to store the value in another service and then default it to that value when you load the app is that from angulars point of view they aren't pointing to the exact same object in memory.

You will need to slightly alter you ngOnInit method as follows.

  1. Find the index of the object in the banner array that you have stored based on a key like BannerId.
  2. After that you can then set the selected option using the same this.selectedBanner = this.banners[bannerIdIndex].

By doing this you will be able to get angular pointing to the correct object in the list you are using in your ngFor

Upvotes: 6

Luciano Huguenin
Luciano Huguenin

Reputation: 221

Try this:

import { Component, OnInit} from '@angular/core';
  public banners: any[];

  ngOnInit() {
     banners = [
        {BannerId: 1, BannerDesc: 'AAAA'},
        {BannerId: 2, BannerDesc: 'BBBB'},
        {BannerId: 3, BannerDesc: 'CCCC'},
        {BannerId: 4, BannerDesc: 'DDDD'},
    ];

 }

Use ngOnInit() for two main reasons:

To perform complex initializations shortly after construction. To set up the component after Angular sets the input properties.

Upvotes: 0

Related Questions