【问题标题】:Select default option value from typescript angular 6从 typescript angular 6 中选择默认选项值
【发布时间】:2018-12-03 04:39:56
【问题描述】:

我有一个这样的选择 html:

<select ng-model='nrSelect' class='form-control'>                                                                
    <option value='47'>47</option>
    <option value='46'>46</option>
    <option value='45'>45</option>
</select>

如何从打字稿中选择默认值,例如 47?

【问题讨论】:

  • nrSelect 设置为默认值。顺便说一句,如果你想绑定工作,你也需要将其更改为[(ngModel)]

标签: angular typescript dropdown


【解决方案1】:

app.component.html

<select [(ngModel)]='nrSelect' class='form-control'>
  <option value='47'>47</option>
  <option value='46'>46</option>
  <option value='45'>45</option>
</select>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  nrSelect = 47
}

【讨论】:

    【解决方案2】:

    首先或所有您使用的 ng-model 被认为是 angularjs 语法。使用[(ngModel)] 代替默认值

    App.component.html

    <select [(ngModel)]='nrSelect' class='form-control'>
        <option value='47'>47</option>
        <option value='46'>46</option>
        <option value='45'>45</option>
    </select>
    

    App.component.ts

    import { Component } from '@angular/core'; 
    @Component({ 
        selector: 'my-app', 
        templateUrl: './app.component.html', 
        styleUrls: [ './app.component.css' ] 
    }) 
    
    export class AppComponent { 
        nrSelect:string = "47" 
    }
    

    【讨论】:

    • 您输入了nrSelect 作为字符串,并使用了数字文字,所以我认为这不会编译
    • 我正在使用 Angular 9,这实际上是我发现它工作的唯一方法
    【解决方案3】:

    你可以这样做:

    <select  class='form-control' 
            (change)="ChangingValue($event)" [value]='46'>
      <option value='47'>47</option>
      <option value='46'>46</option>
      <option value='45'>45</option>
    </select>
    
    // Note: You can set the value of select only from options tag. In the above example, you cannot set the value of select to anything other than 45, 46, 47.
    

    Here, you can ply with this.

    【讨论】:

      【解决方案4】:

      我对 Angular6 也有类似的问题。经过很多帖子。我必须在 app.module.ts 中导入 FormsModule,如下所示。

      import {FormsModule} from '@angular/forms';
      

      然后我的 ngModel 标签工作了。请试试这个。

      <select [(ngModel)]='nrSelect' class='form-control'>                                                                
                                      <option [ngValue]='47'>47</option>
                                          <option [ngValue]='46'>46</option>
                                          <option [ngValue]='45'>45</option>
      </select>
      

      【讨论】:

        【解决方案5】:

        正确的方法是:

        <select id="select-type-basic" [(ngModel)]="status">
            <option *ngFor="let status_item of status_values">
            {{status_item}}
            </option>
        </select>
        

        如果值是动态的,则应避免在选项中使用值,因为这将设置“选择字段”的默认值。默认选择应与 [(ngModel)] 绑定,选项应同样声明。

        status : any = "47";
        status_values: any = ["45", "46", "47"];
        

        【讨论】:

          【解决方案6】:

          对于反应形式,我设法通过使用以下示例使其工作(47 可以替换为其他值或变量):

          <div [formGroup]="form">
            <select formControlName="fieldName">
              <option
                  *ngFor="let option of options; index as i"
                  [selected]="option === 47"
              >
                  {{ option }}
              </option>
            </select>
          </div>
          

          【讨论】:

          • 我在 Angular 11 上试过这个。不工作。我通过在类端设置解决了这个问题:this.form.setValue({fieldName: 47});
          【解决方案7】:

          我认为最好的方法是将它与 ngModel 绑定。

          <select name="num" [(ngModel)]="number">
                          <option *ngFor="let n of numbers" [value]="n">{{n}}</option>
                        </select>
          

          并在ts文件中添加

          number=47;
          numbers=[45,46,47]
          

          【讨论】:

          • 这很好用,但是如果你不注意的话会有一个小问题。即使您在此处进行了操作,但如果控件位于表单内,您必须包含 name='something' 并不明显。没有它就行不通。
          【解决方案8】:

          我通过这样做来管理这个 =>

          <select class="form-control" 
                  [(ngModel)]="currentUserID"
                  formControlName="users">
                  <option value='-1'>{{"select a user" | translate}}</option>
                      <option 
                      *ngFor="let user of users"
                      value="{{user.id}}">
                      {{user.firstname}}
             </option>
          </select>
          

          【讨论】:

            【解决方案9】:

            HTML

            <select class='form-control'>
                <option *ngFor="let option of options"
                [selected]="option === nrSelect"
                [value]="option">
                    {{ option }}
                </option>
            </select>
            

            打字稿

            nrSelect = 47;
            options = [41, 42, 47, 48];
            

            【讨论】:

              【解决方案10】:

              在我的例子中,我使用相同的标记来编辑现有实体,或创建一个全新的实体(到目前为止)。

              我想在创建模式中显示选择元素中“选择”的默认值,同时在编辑模式中显示来自后端的值。

              我的解决办法是:

              <select [(ngModel)]="entity.property" id="property" name="property" required>
                <option disabled hidden value="undefined">Enter prop</option>
                <option *ngFor="let prop of sortedProps" value="{{prop.value}}">{{prop.displayName}}</option>
              </select>
              

              对于常规可用选项,我使用sortedProps 数组来提供选项选择。但这不是这里的重要部分。

              我的诀窍是设置value="undefined" 以让 angular-model-binding (?) 在创建模式下自动选择此选项。不知道它是否是一个黑客,但正是我想要的。不需要额外的 typeScript。

              此外,sepcifing hidden 确保在我的情况下该选项不可选择,而 required 确保表单无效,除非在那里选择了某些内容。

              【讨论】:

                【解决方案11】:

                如果您使用 Angular 的 FormBuilder,这是可行的方法(至少对于 Angular 9):

                HTML 视图:yourelement.component.html

                使用[formGroup] 引用表单变量,使用formControlName 引用表单的内部变量(均在TypeScrit 文件中定义)。最好使用[value] 来引用某种类型的选项ID。

                <form [formGroup] = "uploadForm" (ngSubmit)="onSubmit()">
                   . . .html
                   <select class="form-control" formControlName="form_variable" required>
                       <option *ngFor="let elem of list" [value]="elem.id">{{elem.nanme}}</option>
                   </select>
                   . . .
                </form>
                

                逻辑文件:yourelement.component.ts

                FormBuilderobject 的初始化中,在ngOnInit() 函数中,设置您希望作为默认选择的默认值。

                . . .
                // Remember to add imports of "FormsModule" and "ReactiveFormsModule" to app.module.ts
                import { FormBuilder, FormGroup } from '@angular/forms';
                . . .
                
                export class YourElementComponent implements OnInit {
                  // <form> variable
                  uploadForm: FormGroup;
                
                  constructor( private formBuilder: FormBuilder ){}
                
                  ngOnInit() {
                     this.uploadForm = this.formBuilder.group({
                          . . .
                          form_variable: ['0'], // <--- Here is the "value" ID of default selected
                          . . .
                     });
                  }
                }
                

                【讨论】:

                  【解决方案12】:

                  除了前面提到的,你还可以使用[attr.selected]指令来选择一个特定的选项,如下:

                  <select>
                      <option *ngFor="let program of programs" [attr.selected]="(member.programID == program.id)">
                          {{ program.name }}
                      </option>
                  </select>
                  

                  【讨论】:

                    【解决方案13】:
                    <select class="form-control" [value]="defaultSelectedCurrency" formControlName="currency">
                    <option *ngFor="let item of currency" [value]="item.value" [selected]="item.isSelected">{{item.key}}</option>
                    </select>
                    
                    currency = [
                        { key: 'USD', value: 'USD', isSelected: true },
                        { key: 'AUD', value: 'AUD', isSelected: false }
                      ];
                      defaultSelectedCurrency: string;
                    
                     ngOnInit() {
                        this.defaultSelectedCurrency = this.currency[0].value;
                    }
                    

                    【讨论】:

                      【解决方案14】:

                      您可以像在 angular 9 中一样使用波纹管

                       <select [(ngModel)]="itemId"  formControlName="itemId" class="form-control" >
                                <option [ngValue]="" disabled>Choose Gender</option>             
                                <option *ngFor="let item of items"  [ngValue]="item .id" [selected]="item .id == this.id"  >
                                   {{item.name}}
                                </option>
                         </select>
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2019-02-21
                        • 2018-12-05
                        • 2017-02-05
                        • 1970-01-01
                        • 2018-07-24
                        • 2018-04-26
                        相关资源
                        最近更新 更多