Getting data from a form using two way binding in angular

Lets continue our work with angular. We are going to create a form and get the data from the form. We could eventually use this data to post to an API.

The first thing we need to do is add some imports to our module. Angular apps are separated by modules. We haven’t really looked at ours as yet so lets check it out.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule} from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We need the FormsModule to do two way binding. To add the FormsModule we had to add an import statement.

import { FormsModule} from '@angular/forms';

Next we add it to the imports array in the module that is the app.module.ts file.

  imports: [
    BrowserModule,
    FormsModule
  ],

Once we do this we have access to the FormsModule. We need it to use directives that perform two way binding.

In our component class we add the attributes we need to bind to our form.

export class AppComponent {
  title = 'Hello World';
  name = 'Wynton Franklin';
  description = 'This is a description';
  prof = '';
  terms = true;
  professions = [
      'Accountant',
      'Engineering',
      'Information Technology'
  ];
}

We also add some functions that we use in our views. Lets check them out.

How the form ui looks

We add two way binding on our input elements. The name input is show below.

<input class="input" [(ngModel)]="name" type="text" placeholder="Text input"&gt;

We use the syntax [(ngModel)] we equate this to the class attribute being referenced in this case name. Lets look at the other form elements.

<textarea class="textarea" [(ngModel)]="description" placeholder="e.g. Hello world"&gt;</textarea&gt;

A textarea binding is executed the same way. However the select input is something special. Check it out below.

<select [(ngModel)]="prof"&gt;
            <option *ngFor="let profession of professions" value="{{ profession }}"&gt;
              {{ profession }}
            </option&gt;
</select&gt;

The select statement binding is like the others. We have the [(ngModel)] = "prof". However note that we use the professions array from the class to show the options in the select input. You don’t have to do this. You can just manually insert the options but this way is dynamic and that is the aim.

So we loop through the professions array using the *ngFor directive.

 <option *ngFor="let profession of professions" value="{{ profession }}"&gt;

The next input is a checkbox. We bind this the normal way as well.

<input type="checkbox" [(ngModel)] ="terms"&gt;

We can get true or false values based on whether it is checked or not.

We added two actions. One action submits the form. This prints the data to the console. The second action cancels the form. This clears the bounded variables in the class which in turns clears the variables in the view elements.

The HTML looks like below

 <button (click)='saveForm()' class="button is-link"&gt;Submit</button&gt;
Output from press the save button

The saveForm function is shown below

  saveForm(): void {
     console.log(`Form data saved- name=>${this.name}
     |  description=>${this.description} |
      profession=>${this.prof} |
      checkbox=>${this.checkBoxStatus()}`);
  }

We can access our class attributes using the keyword this. We covered this in previous articles. We also have a checkboxstatus function. Check it out below.

  checkBoxStatus(): string {
    if (this.terms) {
      return `Active`;
    }
    return `InActive`;
  }

We have it typed as string because we return a string. All it does is check the items attribute. If it is true then the checkbox is active.

We clear our form using the clearForm() function.

  clearForm(): void {
    this.name = '';
    this.description = '';
  }

We just set the attributes to an empty string. Since the attributes are bound the changes will be reflected in the form.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s