Angular 4: Data Binding Two-Way-Binding

Initially the button is disabled until a username is input, after which time it is possible to reset the username by clicking the button.


In app.component.ts he simply declare two variables and set ‘username’ to an empty string. The function clears the string and resets the username.

export class AppComponent {
username: string = '';
allowButton: boolean = false;
onUsernameReset(){
this.username = '';
}
}

In app.component.html we use [(ngModel)] for two-way-databinding. This uses both square and round brackets. The input is set to ‘username’ and because of the two-way-binding this is available everywhere, e.g. for string interploation on the next line using {{ username }} and for property binding [disabled]=”!username”

<div class="container">
<div class="row">
<div class="col-md-4">
<label for="box">Username:</label>
<input name="box" type="text" class="form-control" [(ngModel)]="username"/>
<p> {{ username }} </p>
<button class="btn btn-primary" [disabled]="!username" (click)="onUsernameReset()">Reset username</button>
</div>
</div>
</div>

The ‘click’ event is put in round brackets and it calls the function onUsernameReset() which can be found in app.component.ts

Angular 4: Data Biding Event Binding

When an event occurs i.e. clicking a button we want a function onButton() to be called.

In app.component.ts we have the function onButton() which simply logs a few words to the console,

export class AppComponent {
onButton(){
console.log("You pressed it, well done!")
}
}

In app.component.html the event, in this case ‘click’, is in round brackets,

<button class="btn btn-primary">Button</button>