【问题标题】:Angular 2 - Setting selected value on dropdown listAngular 2 - 在下拉列表中设置选定值
【发布时间】:2016-10-24 10:27:19
【问题描述】:

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

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

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

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

这是一个显示问题的 plunker。

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

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

但下拉菜单仍然显示为空。

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

Angular 2 Set begin value of select

Binding select element to object in Angular 2

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

【问题讨论】:

    标签: typescript angular angular2-forms


    【解决方案1】:

    在我的情况下,我从我的 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>
    

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

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

    然后像这样分配它

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

    现在默认设置正确的值。

    【讨论】:

      【解决方案2】:
       <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;
      

      这工作正常...:)

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

          实际上,如果您使用 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"
          

          【讨论】:

            【解决方案5】:

            这对我有用。

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

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

            【讨论】:

              【解决方案6】:

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

              【讨论】:

                【解决方案7】:

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

                 <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]”有效。 (“使用 [(ngModel)] 绑定的示例”下的示例)
                • a
                【解决方案8】:

                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>
                

                【讨论】:

                • 有一个错字:name属性应该是status
                • 很好的解决方案,为我工作。谢谢
                【解决方案9】:

                car.colour 设置为您希望最初选择的值通常是可行的。

                car.colour被设置时,你可以删除[selected]="car.color.id == x.id"

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

                【讨论】:

                • 哇,如果 value 实际上是字符串,[ngValue] 似乎搞砸了
                • 不,不应该。如果您将ngFor 与字符串一起使用,特别是如果您编辑此字符串(在&lt;input&gt; 元素中),您可能需要ngForTrackBy stackoverflow.com/questions/40863074/… ngValue 或只是value 不应该有所作为。
                • 请注意:调用 .patchValue 也可以,传递等效的“值”。前任。 formGroup.get('select_to_change').patchValue("the_value_1")。或者,如果您在构建(反应式表单)表单时获得了值,则可以传递给控件: new FormControl("the_value_1", /** validations */)
                • @Félix 对,对于模型驱动的表单,这是可行的方法。
                【解决方案10】:

                感谢 Günter 的提示,它让我朝着正确的方向前进。我的解决方案中有一个不匹配的“颜色”拼写导致问题,我需要在模板 html 中使用“ngValue”而不是“值”。

                这是使用 ngModel 对象和选择列表选项并避免使用 [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;
                }
                

                【讨论】:

                • 我认为
                猜你喜欢
                • 1970-01-01
                • 2020-01-11
                • 1970-01-01
                • 2012-06-09
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多