为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Angular 在下拉列表中选择的设置

使用 Angular 在下拉列表中选择的设置

千巷猫影 2024-01-22 15:47:25
我在下拉列表中显示了一个列表,但它将默认显示为空白,而不是下拉列表中的第一项。我尝试添加let i = 0然后[selected]="i = 0",但这似乎没有将默认项目设置为第一项,但是我从 收到了正确的值i。下面是我的代码:<div class="form-group">    <label for="userName">User Name</label>    <select formControlName="userName" class="form-control" (change)="userChange($event)">      <option *ngFor="let row of usersModel;let i = index" value="{{ row.id }}" [selected]="i == 0">{{ row.userName }} {{ i }}</option>    </select></div>这是我的 TypeScript 文件:    import { Component, OnInit } from '@angular/core';import { UserAdminService } from '../../services/user-admin.service';import { FormBuilder, Form, FormControl, FormGroup } from '@angular/forms';import { Router } from '@angular/router';@Component({  selector: 'lib-add-user-to-role',  templateUrl: './add-user-to-role.component.html',  styleUrls: ['./add-user-to-role.component.css']})export class AddUserToRoleComponent implements OnInit {  addUserToRoleForm: FormGroup;  rolesModel: any[];  usersModel: any[];  selectedRole: string;  selectedUser: string;  constructor(private userAdminService: UserAdminService, private formBuilder: FormBuilder, private router: Router) {    var roleControl = new FormControl('');    var userControl = new FormControl('');    this.addUserToRoleForm = formBuilder.group({ roleName: roleControl, userName: userControl });  }  ngOnInit() {this.userAdminService.getRoles().subscribe(roles => {  this.rolesModel = roles;  this.selectedRole = this.rolesModel[0].name;  this.userAdminService.getUsersNotInRole(this.selectedRole).subscribe(users => {    this.usersModel = users;    this.selectedUser = this.usersModel[0].id;    console.log(this.usersModel[0].userName);    this.addUserToRoleForm.controls['roleName'].setValue(this.rolesModel[0].name);    this.addUserToRoleForm.controls['userName'].setValue(this.usersModel[0].userName);  });});  }  userChange(event: any) {    this.selectedUser = event.target.value;    console.log('Selected ' + this.selectedUser);  }
查看完整描述

2 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

如果您使用的是响应式表单,则无需使用[selected]Nor (change),只需在创建表单时为 userName 赋予值即可


使用构造函数


const firstId=usersModel[0].id

this.form=new FormGroup({

   userName:new FormControl(firstId)

})

使用表单生成器


const firstId=usersModel[0].id

this.form=this.fb.group({

 userName:firstId

})

创建表单后使用 setValue


   const firstId=usersModel[0].id

   this.form.get('userName').setValue(firstId)


查看完整回答
反对 回复 2024-01-22
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

当您使用 Angular 反应形式时,请尝试将逻辑保留在ts文件本身中。

使用setValue(),您可以为控件设置默认值。

要设置表单控件的默认值,您可以这样,

this.form.controls['country'].setValue(this.countries[0].id)

在模板中使用它,

<option *ngFor="let country of countries" [value]="country.id">
    {{ country.name }}
    </option>

工作堆栈闪电战

参考:

完整的示例代码类似于,

应用程序组件.ts

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

import { FormGroup, FormControl } from '@angular/forms';

import {Country} from './country';


@Component({

  selector: 'my-app',

  templateUrl: './app.component.html',

  styleUrls: [ './app.component.css' ]

})

export class AppComponent  {

  countries = [

    {

      id: 'us',

      name: 'United States'

    },

    {

      id: 'uk',

      name: 'United Kingdom'

    },

    {

      id: 'ca',

      name: 'Canada'

    }

  ];


  form: FormGroup;


  ngOnInit(){

      this.form = new FormGroup({

        country: new FormControl('')

     });

     this.form.controls['country'].setValue(this.countries[0].id)

  }


}

应用程序组件.html


<form [formGroup]="form">

    <select formControlName="country">

        <option *ngFor="let country of countries" [value]="country.id">

            {{ country.name }}

        </option>

    </select>

</form>


查看完整回答
反对 回复 2024-01-22
  • 2 回答
  • 0 关注
  • 32 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信