Angular 2 - Data Binding

  1. Add an Input field which updates a property ('username') via Two-Way-Binding
  2. Output the username property via String Interpolation (in a paragraph below the input)
  3. Add a button which may only be clicked if the username is NOT an empty string
  4. Upon clicking the button, the username should be reset to an empty string

How The Reqs Above Were Implemented In The Code Below

  • The input form field was added on line 12 of .html, and also contains the Angular 2 way binding code of [(ngModel)]="username", which will bind with the property "username" that was added on line 9 in .ts.
  • IMPORTANT: In order for the ngModel declaration to work it must be imported in the app.module.ts file in the import section (line 3) and then declared in the imports: array of @NgModule (line 14). (It's usually automatically built in when components are created from the CLI but make sure!)
  • Line 13 of .html the username is displayed as entered (keystroke). On line 14 of .html the button is defined but is bounded to the disabled property of the button, so if the username property is empty (and because it's 2 way bound we simply check the property on the app.component.ts file) it's disabled. The (click)="username=''" is the listener required to actually cause the username to display nothing when the username property is empty.

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  username = '';
}

app.component.html

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <ol>
        <li>Add a Input field which updates a property ('username') via Two-Way-Binding</li>
        <li>Output the username property via String Interpolation (in a paragraph below the input)</li>
        <li>Add a button which may only be clicked if the username is NOT an empty string</li>
        <li>Upon clicking the button, the username should be reset to an empty string</li>
      </ol>
      <hr>
      <label>Username</label>
      <input type="text" class="form-control" [(ngModel)]="username">
      <p>{{ username }}</p>
      <button
        class="btn btn-primary"
        [disabled]="username === ''"
        (click)="username = ''">Reset User</button>
    </div>
  </div>
</div>

app.module.ts

	import { BrowserModule } from '@angular/platform-browser';
	import { NgModule } from '@angular/core';
	import { FormsModule } from '@angular/forms';
	import { HttpModule } from '@angular/http';
	
	import { AppComponent } from './app.component';
	
	@NgModule({
	  declarations: [
		AppComponent
	  ],
	  imports: [
		BrowserModule,
		FormsModule,
		HttpModule
	  ],
	  providers: [],
	  bootstrap: [AppComponent]
	})
	export class AppModule { }

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/angular2/angular-2-data-binding/