1

I want to ask about how I can set option to be default selected?

<form [formGroup]="form2">
  <select formControlName="drop">
    <option disabled>Choose one</option>
    <option *ngFor="let example of examples" [value]="example.id" [disabled]="example.isDisabled" [selected]="example.isSelected">{{ example.name }}</option>
  </select>
</form>

Component:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-drop-down-list',
  templateUrl: './drop-down-list.component.html',
  styleUrls: ['./drop-down-list.component.css']
})
export class DropDownListComponent implements OnInit {

  public form = new FormGroup({
    drop: new FormControl('',
      Validators.required,
    ),
  });

  public form2 = new FormGroup({
    drop: new FormControl('',
      Validators.required,
    ),
  });

  examples = [{
    id: 1, name: 'Test1', isSelected: false, isDisabled: true,
  },
  {
    id: 2, name: 'Test2', isSelected: true, isDisabled: false,
  },
  {
    id: 3, name: 'Test3', isDisabled: false,
  }
  ];

  constructor() { }

  ngOnInit() {
  }

  onSubmit(form) {
    console.log(form);
  }

}

I was searching on stack but I don't want to mix reactive forms with ngModel, also I don't wan't to use patchValue because It only set default value without choosing element in list. Thanks for help!

1 Answer 1

2

if you want option to be selected then do like this , just pass id value in your formcontrol intialization

  public form2 = new FormGroup({
    drop: new FormControl(this.examples[0].id,
      Validators.required,
    ),
  });

or if you dont want to initialization immediately and want later on then make use of setValue method, below is required when you are fecthing data from server and want to set value i just hard coded value just to show as example , you should replace with the value you get from server

form2.get('drop').setValue('1');

html should be as below no need of [selected]

 <select formControlName="drop">
    <option disabled>Choose one</option>
    <option *ngFor="let example of examples" [value]="example.id" [disabled]="example.isDisabled" >{{ example.name }}</option>
  </select>
Sign up to request clarification or add additional context in comments.

4 Comments

I would have gone for new FormControl(this.examples[0].id, Validators.required) but otherwise I agree
@trichetriche - ok lets do the change , updated answer
Thanks! I have only one more question, we're I can find list of attributes that doesn't work normal with angular?
@Gnex - normally html attributes not work with anuglar , for example tooltip on textbox or

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.