0

I have a list displayed in a dropdownlist, but it displays the default as a blank and not as the first item in the dropdown.

I have tried adding let i = 0 and then [selected]="i = 0", but this does not seem to set the default item to the first item, however I am receiving the correct value back from i.

Below is my code:

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

Here is my TypeScript File:

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

  AddUserToRole() {
    this.userAdminService.addUserToRole(this.selectedUser, this.selectedRole)
      .subscribe(result => {
        if (result.success) {
          this.router.navigate(['/roleusermaint']);
        }
        else {
          console.log('Error Received on adding user to role');
        }
      });
  }
}

As you can see I added {{ i }} in the text to make sure it shows the value of i and it does:

enter image description here

What am I missing ?

Thanks for any help!

5
  • I know it seems like a small problem, but adding a stackblitz with as minimal content as possible is helpful to reproduce the issue. Commented Apr 21, 2020 at 8:53
  • Ah I hear you. I will check into it and see if I can figure it out. Thanks for the mention Commented Apr 21, 2020 at 8:57
  • @AxleWack, Does this help you?? stackblitz.com/edit/angular-reactive-forms-select-option-jfuqqc .. It sets the first value to the select box.. When using reactive form, try to keep the logics in ts file.. Commented Apr 21, 2020 at 9:02
  • I tried that, but does not seem to make a difference :( I have posted my typescript file as well Commented Apr 21, 2020 at 9:23
  • @AxleWack, I have posted it as answer .. Thanks.. Commented Apr 21, 2020 at 10:44

2 Answers 2

1

@Axle, if you're using a Reactive Form, you needn't use [selected] nor (change), just, when you create the form you give value to userName

Using the constructor

const firstId=usersModel[0].id
this.form=new FormGroup({
   userName:new FormControl(firstId)
})

Using formBuilder

const firstId=usersModel[0].id
this.form=this.fb.group({
 userName:firstId
})

Using setValue, after create the form

   const firstId=usersModel[0].id
   this.form.get('userName').setValue(firstId)
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the reply. I am still very new at angular, but will work through what you have provided and see how I can implement this in my existing code
@MikeS. take alook to the simple stackblitz: stackblitz.com/edit/…, if you change userName:new FormControl() by userName:new FormControl(1) work propertly, else not
@AxleWack, you need put the setValues:this.addUserToRoleForm.controls['roleName'].setValue(this.selectedRole); and this.addUserToRoleForm.controls['userName'].setValue(this.selectedUser); INSIDE the subscribe function
Correct you are. I have made the change and tested the value being returned with console.log, but the control is still not setting it as the default value :( I have updated my question
@Alex, take account your select's options has as value {{row.id}}, not row.userName, so you need give the id value to the control- I suppose that was an error typo, sorry- futhermore I prefer the way this.addUserToRoleForm.get('roleName') than this.addUserToRoleForm.controls['roleName']
|
0

As you are using Angular reactive form, try to keep the logic in ts file itself.

Using setValue(), you can set the default value to a control.

To set the default value to form control you could to it like,

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

In template use it like,

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

Working Stackblitz

Ref:

A complete sample code would be something like,

app.component.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)
  }

}

app.component.html

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.