angularform-control

setValue on FormControl is not reflected in View


I want to load an existing value into a FormControl to be able to update the value in my database.

My code (shortened and boiled down to an example) looks as follows. Clicking the edit button shall load the referring name from the array into the FormControl.

App-Component

import { Component } from '@angular/core';
import {FormControl, ReactiveFormsModule} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent  {

  nameForm = new FormControl(['']);
  names = ['Peter', 'Bob', 'Mary']

  updateName (id : number): void {
      this.nameForm.setValue(this.names[id]);
  }   
}

HTML-Template

 <table>
            <tr>
              <th>Id</th>
              <th>Name</th>
              <th>Actions</th>
            </tr>
            <tr *ngFor="let name of names; index as i">
                <td>{{i + 1}}  : </td><td>{{name}}</td>
                  <td>
                    <button (click)="updateName(i)">Edit</button>
                  </td>
            </tr>
    </table>
<input type="text" formControlName="nameForm">

I have constructed an example on https://stackblitz.com/edit/angular-m7vm4y. Clicking on edit does not set the value into the FormControl. Where is my mistake?

Thanks and best!


Solution

  • Please try adding a FormGroup as shown below:

    HTML:

    <form [formGroup]="form">
     <input type="text" formControlName="name">
    </form>
    

    TS:

    name = new FormControl(['']);
    names = ['Peter', 'Bob', 'Mary']
    form: FormGroup;
    
    constructor(private fb: FormBuilder){
     this.form=this.fb.group({
       name:['']
     })
    }
    
    updateName (id : number): void {
      this.form.get('name').setValue(this.names[id]);
    }
    

    For more info refer:

    https://angular.io/guide/reactive-forms

    Hope this helps