Angular 2 - 在下拉列表中设置选定值

Angular 2 - Setting selected value on dropdown list

我 运行 在 Angular 2 的下拉列表中预选值时遇到问题。

我在成功绑定到下拉列表的组件中设置了一组颜色。我遇到的问题是在页面初始化时预先选择一个值。

[selected]="car.color.id == x.id" 应该选择已在汽车模型上设置的值 this.car.color = new Colour(-1,''); 但这仅在我将汽车颜色 ID 设置为列表中的最后一项时有效(在这种情况是黑色的)this.car.color = new Colour(4,'');

我使用的是最新版本的 Angular (rc3),并且在 rc1 和 rc2 中遇到了同样的问题。

这里有一个 plunker 显示了这个问题。

https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview

另一个奇怪的方面是,在查看元数据时 Angular 已将所选值设置为 true。

但下拉列表仍然显示为空。

这似乎是与这些相关问题不同的问题。

Angular 2 Set begin value of select

How to use select/option/NgFor on an array of objects in Angular2

此致

史蒂夫

组件模板

   <div>
        <label>Colour</label>
        <div>
            <select [(ngModel)]="car.colour"">
                <option *ngFor="let x of colours" [value]="x.id" [selected]="car.color.id == x.id">{{x.name}}</option>
            </select>
        </div>
    </div>

组件

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 = new 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.colours.push(new Colour(3, 'Orange'));
        this.colours.push(new Colour(4, 'Black'));

        this.car = new Car();
        this.car.color = new Colour(-1,'');        
    }
}

export class Car
{
    color:Colour;
}

export class Colour
{
    constructor(id:number, name:string) {
        this.id=id;
        this.name=name;
    }

    id:number;
    name:string;
}

car.colour 设置为您希望最初选择的值通常有效。

设置car.colour时,可以去掉[selected]="car.color.id == x.id"

如果值不是字符串,则必须使用 [ngValue]="..."[value]="..." 只支持字符串。

感谢 Günter 的提示,它让我朝着正确的方向前进。我的解决方案中 'color' 的拼写不匹配导致了问题,我需要在模板 html 中使用 'ngValue' 而不是 'value'。

这是使用 ngModel 对象和 select 列表选项并避免使用 [selected] 属性的完整解决方案。

我已经更新了 Plunker 以显示完整的工作解决方案。 https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview

组件模板

 <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>

组件

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;
}

Angular 2个简单的下拉选择值

它可能对某些人有帮助,因为我只需要显示选定的值,不需要在组件中声明某些东西等等。

如果您的状态来自数据库,那么您可以通过这种方式显示所选值。

<div class="form-group">
    <label for="status">Status</label>
    <select class="form-control" name="status" [(ngModel)]="category.status">
       <option [value]="1" [selected]="category.status ==1">Active</option>
       <option [value]="0" [selected]="category.status ==0">In Active</option>
    </select>
</div>

此示例解决方案适用于反应形式

 <select formControlName="preferredBankAccountId" class="form-control">
                <option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >
                  {{item.nickName}}
                </option>
              </select>

在组件中:

this.formGroup.patchValue({
        preferredBankAccountId:  object_id_to_be_pre_selected
      });

您也可以在初始化 formGroup 时或之后提供此值,具体取决于您的要求。

您也可以通过使用 [(ngModel)] 绑定来完成此操作,而无需初始化您的 formControl。

[(ngModel)] 绑定示例

 <select [(ngModel)]="matchedCity" formControlName="city" class="form-control input-sm">
                  <option *ngFor="let city of cities" [ngValue]="city">{{city.cityName}}</option>
                </select>

这里,matchedCity 是城市中的对象之一。

我想补充一点,[ngValue]="..." 支持字符串,但如果它代表数字,则需要添加简单的引号,例如 [ngValue]="'...'"。这是对 Günter Zöchbauer 回答的补充。

这对我有用。

<select formControlName="preferredBankAccountId" class="form-control" value="">
    <option value="">Please select</option>    
    <option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >{{item.nickName}}</option>
</select>

不确定这是否有效,如果有误请指正。
如果这不应该是这样的话,请纠正我。

实际上,如果您使用 ReactiveForms,我发现这种方式更容易完成:

如果表单是这样定义的:

public formName = new FormGroup({

    fieldName: new FormControl("test") //where "test is field default value"

});

那就是您可以更改其值的方式:

this.formName.controls.fieldName.setValue("test 2"); //setting field value to "test 2"

如果您的值来自数据库,请以这种方式显示选定的值。

<div class="form-group">
    <label for="status">Status</label>
    <select class="form-control" name="status" [(ngModel)]="category.status">
       <option [value]="1" [selected]="category.status ==1">Active</option>
       <option [value]="0" [selected]="category.status ==0">In Active</option>
    </select>
</div>
 <div class="col-md-3 col-sm-3">
                        <label>Outlet Ready</label>
                            <div>
                                <select class="form-control"  
                                     [(ngModel)]="selectedColor">
                               <option *ngFor="let x of colours" [ngValue]="x" >{{x.name}}</option>
                                </select>
                            </div>    
                    </div>

Compoent.ts

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;

这工作正常...:)

在我的例子中,我从 api 中返回字符串值,例如:“35”,在我的 HTML 中,我使用的是

       <mat-select placeholder="State*" formControlName="states" [(ngModel)]="selectedState" (ngModelChange)="getDistricts()">
            <mat-option *ngFor="let state of formInputs.states" [value]="state.stateId">
              {{ state.stateName }}
            </mat-option>
          </mat-select>

就像评论中提到的其他人一样,我猜值将只接受整数值。所以我所做的是在我的组件 class 中将我的字符串值转换为整数,如下所示

          var x = user.state;
          var y: number = +x;

然后像这样赋值

  this.EditProfileForm.get('states').setValue(y);

现在默认设置正确的值。