0

I have a FormGroup with 2 FormControls "name" and "type". Type is a select html input with options generated with a ngFor loop. So when I edit my Element the Component with the FormGroup shows up, it loads the Element I want to edit and automatically fills in the Name of the Element in the name input field. What I trying to do is the same with the type field.

mycomponent.html

<form [formGroup]="myForm" (ngSubmit)="onMyFunktion()">
  <div class = "form-group">
      <label for="name">Name</label>
      <input formControlName="name" type="text" id="name" class="form-control" required >
  </div>
  <div class="form-group">
    <label for="type">Type</label>
    <select formControlName="type" id="type" class="form-control"  required >
      <option *ngFor="let Type of types" value="Type.Id">{{Type.Name}}</option>
    </select>
  </div> 
  <button type="submit" [disabled]="!MyForm.valid"  class ="btn btn-primary">save</button>
  <button type="button" (click)="onBack()" class ="btn btn-success">Back</button>
</form>

mycomponent.ts

ngOnInit()
  {
  this.MyForm = new FormGroup
  ({
    name: new FormControl(this.myElement.Name), 
    type: new FormControl() // myElement only has its Name and the Id of the type not the type name
  })
 }
Kajot
  • 1,043
  • 2
  • 15
  • 22

1 Answers1

0

When you are dealing with objects angular can't detect automatically the default value, so you have to add the compareWith attribute like this:

<select formControlName="type" id="type" class="form-control"  required [compareWith]="byTypeId" >

and in your component class, you have to write, the byTypeId method like this:

byTypeId(a, b) {
  return a === parseInt(b, 10);
}

PS: I am supposing that your type id is an integer

Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43