Angular 2 - Setting selected value on dropdown list

前端 未结 8 1150
天命终不由人
天命终不由人 2020-12-04 16:29

I have run into an issue in pre-selecting values on a dropdown list in Angular 2.

I set an array of colours in the component which I bind successfully to the drop

相关标签:
8条回答
  • 2020-12-04 17:06

    I would like to add, [ngValue]="..." support strings, but you need to add simple quotes if it represents a number, like [ngValue]="'...'". It was to complement the Günter Zöchbauer answer.

    0 讨论(0)
  • 2020-12-04 17:07

    Thanks for the tip Günter, it got me moving in the right direction. There was a mis-matched spelling of 'color' in my solution which was causing issues and I needed to use 'ngValue' not 'value' in the template html.

    Here is the complete solution using objects for the ngModel and select list options and avoiding use of the [selected] attribute.

    I have updated the Plunker to show the full working solution. https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview

    Component template

     <div>
            <label>Colour</label>
            <div *ngIf="car != null">
                <select [(ngModel)]="car.colour">
                    <option *ngFor="let x of colours" [ngValue]="x" >{{x.name}}</option>
                </select>
            </div>
        </div>
    

    Component

    import { Component, OnInit } from '@angular/core';
    import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';
    
    @Component({
        selector:'dropdown',
        templateUrl:'app/components/dropdown/dropdown.component.html',
        directives:[FORM_DIRECTIVES]
    })
    export class DropdownComponent implements OnInit
    {
        car:Car;
        colours: Array<Colour>;
    
        ngOnInit(): void {
    
            this.colours = Array<Colour>();
            this.colours.push(new Colour(-1, 'Please select'));
            this.colours.push(new Colour(1, 'Green'));
            this.colours.push(new Colour(2, 'Pink'));
    
            this.car = new Car();
            this.car.colour = this.colours[1];        
        }
    }
    
    export class Car  
    {
        colour:Colour;
    }
    
    export class Colour
    {
        constructor(id:number, name:string) {
            this.id=id;
            this.name=name;
        }
    
        id:number;
        name:string;
    }
    
    0 讨论(0)
提交回复
热议问题