Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2, set value of text inputs in form

So I'm trying out some Angular 2 and I like it so far. But I need some help to navigate this new landscape.

I have a form to edit a users details and a list on the side with all my users. When I click on one of the users in the list I want to populate my edit-user-form with the user details (setEditForm(user)).

I've got it working and all. But I must say, it doesn't feel quite right to use ngControl and ngModel at the same time. But maybe it is...

Is this the correct way to do this or have I just got some luck in making it work?

@Component({
  template: `
    <form (ngSubmit)="editUser(f.value)" #f="ngForm">
      <input ngControl="nameInp" [ngModel]="selectedUser.name" type="text">
      <input ngControl="ageInp" [ngModel]="selectedUser.age" type="text">
      <input ngControl="cityInp" [ngModel]="selectedUser.city" type="text">

      <button type="submit">Save</button>
    </form>
)}

export class AdminComponent {
 selectedUser:UserModel;

 constructor() {
    this.selectedUser = new UserModel;
  }

  setEditForm(user:UserModel) {
    this.selectedUser = user;
  }

  editUser(form:any) {
    // Update DB with values
    console.log(form['nameInp']);
    console.log(form['ageInp']);
    console.log(form['cityInp']);
  }
}
like image 300
mottosson Avatar asked Mar 11 '16 20:03

mottosson


1 Answers

Sure you can use ngControl / ngFormControl and ngModel at the same time. From the Angular2 documentation (https://angular.io/docs/ts/latest/guide/forms.html):

  • two-way data binding with [(ngModel)] syntax for reading and writing values to input controls

  • using ngControl to track the change state and validity of form controls

  • displaying validation errors to users and enable/disable form controls

  • sharing information among controls with template local variables

In short, I would use ngModel if I need two-way binding and ngForm / ngFormControl if I need validation but you can mix both.

If you only need to get values and notifications when input values are updated, ngControl / ngFormControl` is enough...

Both allow to detect changes:

  • Event ngModelChange
  • Subscribe on ctrl.valueChanges

You could configure two-way binding for ngModel for your form elements:

<form (ngSubmit)="editUser(f.value)" #f="ngForm">
  <input ngControl="nameInp" [(ngModel)]="selectedUser.name" type="text">
  <input ngControl="ageInp" [(ngModel)]="selectedUser.age" type="text">
  <input ngControl="cityInp" [(ngModel)]="selectedUser.city" type="text">

  <button type="submit">Save</button>
</form>
like image 87
Thierry Templier Avatar answered Nov 02 '22 18:11

Thierry Templier