Property binding angular 4 example

Property binding angular 4 example:

What is property binding ?

Binding html properties like disabled[disabled], class[ngClass] and style[ngStyle] dynamically with component values using angular. You can even create your own custom property using @Input.

Syntax:
[]

Eg: [disabled]

 

Property binding Types:
  • Element property
  • Component property
  • Directive property

In our last tutorial we have seen about event binding and twoway binding. As part of that we have created a simple app,

1. Created two text field with technology name and technology description
2. Added a button which adds both the technology name and the technology description to the array using .push method.
3. ngFor used to iterate and show the added value to the same page.
4. Button will be enabled all the time, this will be disabled here if no values are entered in any of the text fields using property binding.
Have a quick look at this post:

Angular 4 Event Binding + Two Way Databinding Simple Example


Now in this post using property binding “Add New Tech” button will be disabled unless you type something in both the technology name and technology description.

Typescript Code:


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

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

addTechName(){
this.technologies.push({
type:'tech',
techname: this.techName,
techdesc: this.techDesc
});
}


checkFields(){
if(this.techName ==='' || this.techDesc ===''){
return false;
}else{
return true;
}

}
}

checkFields is the method which just checks the techName and techDesc twoway binding variable and returns false if any one of them is empty.

Html Template Code:

<div class="container">
<div class="row">
<h2> Add New Technology </h2>
</div>

<div class="row">
<div class="col-xs-12">
<label for="techN"> Enter Technology Name </label>
<input type="text" [(ngModel)] = "techName" id="techN">


<label for="techD"> Enter Technology Description </label>
<input type="text" [(ngModel)] = "techDesc" id="techD">


<button class="btn btn-success" (click)="addTechName()" [disabled]="!checkFields()">Add New Tech</button>

</div>
<div class="col-xs-12">
<div *ngFor="let technology of technologies">
<p> {{ technology.techname }} | {{ technology.techdesc }} </p>
</div>
</div>
</div>
</div>

 

[disabled]=”!checkFields()”, here [disabled] is the property binding. based on the response from (true/false) from checkFields() method, this button will be either enabled/disabled dynamically.

 

 

Simple Application Screenshots:

 

Property binding angular 4 example

 

Button enabled,

Property binding angular 4 example

 

Value added to array:

Property binding angular 4 example

 

 

527 total views, 3 views today

Leave a Reply

Your email address will not be published. Required fields are marked *