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

我在下拉列表中显示了一个列表,但它将默认显示为空白,而不是下拉列表中的第一项。


我尝试添加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);

  }



千巷猫影
浏览 105回答 2
2回答

蛊毒传说

如果您使用的是响应式表单,则无需使用[selected]Nor (change),只需在创建表单时为 userName 赋予值即可使用构造函数const firstId=usersModel[0].idthis.form=new FormGroup({&nbsp; &nbsp;userName:new FormControl(firstId)})使用表单生成器const firstId=usersModel[0].idthis.form=this.fb.group({&nbsp;userName:firstId})创建表单后使用 setValue&nbsp; &nbsp;const firstId=usersModel[0].id&nbsp; &nbsp;this.form.get('userName').setValue(firstId)

明月笑刀无情

当您使用 Angular 反应形式时,请尝试将逻辑保留在ts文件本身中。使用setValue(),您可以为控件设置默认值。要设置表单控件的默认值,您可以这样,this.form.controls['country'].setValue(this.countries[0].id)在模板中使用它,<option *ngFor="let country of countries" [value]="country.id">     {{ country.name }}     </option>工作堆栈闪电战参考:完整的示例代码类似于,应用程序组件.tsimport { 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5