从typescript angular 6中选择默认选项值

67

我有一个像这样的select html:

<select ng-model='nrSelect' class='form-control'>                                                                
    <option value='47'>47</option>
    <option value='46'>46</option>
    <option value='45'>45</option>
</select>
如何在 TypeScript 中选择默认值,例如 47?

nrSelect 设置为默认值。顺便提一下,如果想让绑定起作用,你还需要将它改为 [(ngModel)] - user184994
18个回答

67

你可以这样做:

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

在这里,你可以玩弄这个。


50

应用程序组件 HTML 文件

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

应用组件的 TypeScript 文件

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

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

28
对于响应式表单,我使用了以下示例使其正常工作(47可以替换为其他值或变量):
<div [formGroup]="form">
  <select formControlName="fieldName">
    <option
        *ngFor="let option of options; index as i"
        [selected]="option === 47"
    >
        {{ option }}
    </option>
  </select>
</div>

3
我在 Angular 11 中尝试过这个方法,但无法正常工作。我通过在类上设置以下内容来解决问题:this.form.setValue({fieldName: 47}); - jlguenego

10
正确的方式是:
<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"];

9

如果你使用Angular的FormBuilder,这是一种可行的方式(至少适用于Angular 9):

HTML视图:yourelement.component.html

使用[formGroup]引用表单变量,并使用formControlName引用表单内部变量(两者在TypeScript文件中定义)。最好使用[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

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

. . .
// 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
          . . .
     });
  }
}

7

首先,你正在使用被认为是 AngularJS 语法的 ng-model。请改用带有默认值的 [(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 输入为字符串,并使用了数字字面量,因此我认为这不会编译。 - user184994
我正在使用 Angular 9,这实际上是我发现它能正常工作的唯一方法。 - dc_Bita98

7

HTML

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

Typescript

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

5

我也遇到了类似的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

我认为最好的方法是将其与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',否则它将无法工作。 - user10484617

4
我通过以下方式来管理这个问题 =>
<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接