Saturday, July 31, 2021

Angular Custom Two-Way Data Binding

In the post Angular Two-Way Data Binding With Examples we saw how two way binding can be done using ngModel and it is a combination of both property binding and event binding. In this post we’ll see how to do custom two way data binding in Angular.

Angular custom two way data binding

You can use a custom property for two way data binding, for example-

<app-counter [(counter)]="counterValue"></app-counter>

Here counter is a property that has two way data binding. In the component you should have a counter property that can be assigned a value and a corresponding event named counterChange. Note that this convention has to be followed, the event name has to be ‘property name + change’.

Angular custom two way data binding example

Here is a simple example of custom two way data binding. There is a child component that displays the counter value and has buttons to decrement or increment counter value.

counter.component.html

<div>
  <label>Value </label> {{counter}}
  <hr/>
  <button class="btn btn-primary" (click)="dec()" title="smaller">-</button>
  <button class="btn btn-primary" (click)="inc()" title="bigger">+</button>
</div> 

counter.component.ts

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-counter',
  templateUrl: './counter.component.html'
})
export class CounterComponent{
  @Input() counter : number;
  @Output() counterChange = new EventEmitter<number>();

  dec(){
    --this.counter;
    this.counterChange.emit(this.counter);
  }
  inc(){
    ++this.counter;
    this.counterChange.emit(this.counter);
  }
}

In the component, counter property is decorated with @Input decorator which means property binding where value of counter is expected from the parent component through this binding.

There is also an event binding done using counterChange. Whenever decrement or increment button is clicked value of counter is changed and that changed value is emitted using counterChange event emitter.

app.component.ts

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

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

app.component.html

<div class="container">
  <div class="row">
    <div class="col-md-10">       
      <app-counter [(counter)]="counterValue"></app-counter>
      <label>Value of the counter is </label> {{counterValue}}
    </div>
  </div>
</div>

Here AppComponent.counterValue is two-way bound to the CounterComponent. counter property of CounterComponent gets its initial value from AppComponent.counterValue ( counterValue = 5 in AppComponent). Clicking the decrement and increment buttons updates the AppComponent.counterValue via the two-way binding.

So, there is a property binding where child property is bound to the parent property and there is also an event binding from child to parent causing the change in counter value.

Initial screen

On clicking decrement.

That's all for this topic Angular Custom Two-Way Data Binding. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Custom Property Binding Using @Input Decorator
  2. Angular Custom Event Binding Using @Output Decorator
  3. Angular Style Binding With Examples
  4. Angular @Input and @Output Example
  5. Angular ngSwitch Directive With Examples

You may also like-

  1. Injector Hierarchy and Service Instances in Angular
  2. Angular - Call One Service From Another
  3. Forms in Angular
  4. Angular Project Structure With File Description
  5. Java String Interview Questions And Answers
  6. Java BlockingQueue With Examples
  7. Spring Boot spring-boot-starter-parent
  8. Apache Avro Format in Hadoop

Friday, July 30, 2021

Angular Custom Event Binding Using @Output Decorator

In the post Angular event binding we saw how event binding allows you to listen and respond to the events sent by the host elements. We can also bind a custom event of an Angular component that’s what we’ll see in this post how to bind custom event in Angular using @Output decorator.


Angular custom event binding

Using custom event binding is a great way for parent and child components to communicate where parent component is informed of any change in the child component. For example following statement in the parent template shows the event binding for the property “onUserSelected” in the child component.

Statement in parent component-

<app-user *ngFor="let user of users" 
            [usr]="user" (onUserSelected)="showUser($event)">

Property in child component-

@Output() onUserSelected: EventEmitter<User>;

@Output decorator, $event and EventEmitter

While doing a custom event binding in Angular three things you will come across are-

  1. @Output decorator
  2. EventEmitter class
  3. $event object

1. @Output decorator

A property in a Component that emits a custom event is decorated with @Output decorator. For example in the statement

@Output() onUserSelected: EventEmitter<User>;

onUserSelected is decorated with @Output() which means this property is going to emit a custom event. That is why this property is of type EventEmitter.

2. EventEmitter class

EventEmitter class is used in components with the @Output to emit custom events synchronously or asynchronously. EventEmitter maintains a list of subscribing instances and register handlers for the event.

EventEmitter class has two methods-

  • emit(value?: T)- Emits an event containing a given value, T signifies the value to emit.
  • subscribe()- Registers handlers for events emitted by this instance.

When we assign an EventEmitter to an output, subscription of instances is automatically done by Angular so you don't need to use this method explicitly in most of the scenarios.

3. $event object

In an event binding, Angular sets up an event handler for the target event. The binding conveys information about the event. This information is encapsulated in $event and may include data values such as an event object, string, or number.

When the event is raised, the handler executes the template statement. Foe example in the following statement

(onUserSelected)="showUser($event)"

(onUserSelected) is the target event

showUser($event) is the template statement.

When the event onUserSelected is raised, template statement, which in our example is showUser($event) method, is executed. Argument of the showUser() method is $event which encapsulates the value passed as method parameter.

Angular custom event binding example

We have got enough information about the event binding and the parts that form the custom event binding. Let’s create an example using that knowledge now. Note than example is created using Angular 9 and Bootstrap 4.

In the example there are two child components UserComponent and UserDataComponent and AppComponent is the parent component.

Initially list of user names is displayed (Done through UserComponent), on clicking any of the user User details are displayed (Done through UserDataComponent).

user.model.ts

In the Model class there are 3 fields name, age and joinDate.

export class User {
  name : string;
  age : number;
  joinDate : Date;
  constructor(name: string, age : number, joinDate : Date) {
    this.name = name;
    this.age = age;
    this.joinDate  = joinDate;
  }
}

app.component.ts (Parent component)

AppComponent uses User model so that is imported. An array of type User is defined and user instances are added to that array in the Constructor. Property selectedUser stores the value of the User which is selected and used to display details for the selected User. When the custom event is raised showUser() method gets called which assigns value to the selectedUser property.

import {Component} from '@angular/core';
import { User } from './user/user.model';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users: User[];
  selectedUser : User;
  constructor(){
    //Adding User instances to users array
    this.users = [new User('Jack', 56, new Date('2005-03-25')),
                  new User('Lisa', 32, new Date('2012-05-09')),
                  new User('Jayesh', 28, new Date('2014-10-21'))
                 ] ;
  }
  showUser(user: User) : void {
    // Setting selected user
    this.selectedUser = user;
  }
}

app.component.html

<h3>Click User to get details</h3>
<app-user 
    *ngFor="let user of users" 
    [usr]="user" (onUserSelected)="showUser($event)">
</app-user>

<user-data *ngIf="selectedUser" [user]="selectedUser"></user-data>

Template has two selectors tags for the child templates. With in the <app-user> selector users array is iterated using ngFor directive and each user instance is bound to the usr property of the child component, onUserSelected is the output property (to emit event).

user.component.ts (Child component)

import { 
    Component, Input, Output, EventEmitter
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  @Input() usr: User;
  @Output() onUserSelected: EventEmitter<User>;
  constructor(){
    this.onUserSelected = new EventEmitter();
  }
  userClicked() : void{
    this.onUserSelected.emit(this.usr);
  }
}

In the child component usr variable is decorated with @Input decorator indicating that parent component can bind to this property.

onUserSelected is decorated with @Output indicating that it will emit an event.

In the userClicked() method using emit method an event is emitted with current user instance as event value which will be encapsulated in $event.

User.component.html

In the template user name is displayed, there is also an even binding for click event which calls the userClicked() method. Execution of userClicked() method results in emitting the even with the user instance as value.

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      <label>Name: </label><span (click)='userClicked()'>{{ usr.name }}</span>
    </div>
  </div>
</div>

userdata.component.ts (Child component)

import { 
  Component, Input
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'user-data',
  templateUrl: './userdata.component.html'
})
export class UserDataComponent{
  @Input() user: User;
}

Another child component UserDataComponent has a property user which is decorated with @Input decorator indicating that parent component can bind to this property. This is property to which selected user is assigned and then used to display user details.

userdata.component.html

This template shows the user details.

<div class="jumbotron">
  <div class="container">
    <h2>User Details</h2>
    <div class="row">
      <div class="col-xs-5 px-3">
        <label>Name: </label> {{ user.name }}      
      </div>
      <div class="col-xs-4 px-3">
        <label>Age: </label> {{ user.age }}
      </div>
      <div class="col-xs-4 px-3">
        <label>Joining Date: </label> {{ user.joinDate | date:'dd/MM/yyyy'}}
      </div>
    </div>
  </div>
</div>

Testing the application

Initially user names are displayed.

Angular Custom Event Binding

When user name is clicked

Custom Event Binding Example

That's all for this topic Angular Custom Event Binding Using @Output Decorator. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Custom Property Binding Using @Input Decorator
  2. Angular Custom Two-Way Data Binding
  3. Angular Style Binding With Examples
  4. Angular Example to Render Multiple Rows
  5. Angular @Input and @Output Example

You may also like-

  1. Angular ngClass Directive With Examples
  2. Angular @Component Decorator
  3. Service in Angular With Examples
  4. Angular Disable Button Example
  5. Multiple Catch Blocks in Java Exception Handling
  6. intern() Method in Java String
  7. Varargs (Variable-length Arguments) in Java
  8. Spring Batch Processing With List of Objects in batchUpdate() Method

Thursday, July 29, 2021

Angular @ViewChild Decorator With Examples

@ViewChild decorator in Angular is used if you want to access any directive, child component or DOM element in the Component class.

Using @ViewChild decorator you can configure a view query, that is done by passing a selector with @ViewChild. For example

@ViewChild('membershipForm') memberForm

Here ‘membershipForm’ is the passed selector.

The change detector looks for the first element or the directive matching the selector in the view DOM and assigns it to the property decorated with @ViewChild.

View queries and ngAfterViewInit callback

View queries are set before the ngAfterViewInit callback is called. That means ngAfterViewInit callback is the best place to manipulate the element or directive by using the reference variable.

ViewChild Metadata Properties

You can pass the following three metadata properties with @ViewChild decorator.

  • selector- The directive type or the name that has to be queried.
  • read- Used to read a different token from the queried elements.
  • static- True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.

read and static properties are optional.

Wednesday, July 28, 2021

Angular Custom Property Binding Using @Input Decorator

In the post Angular Property Data Binding we saw how to bind data to a property of an element. We can also bind a custom property of an Angular component that’s what we’ll see in this post how to bind custom property in Angular using @Input decorator.


Angular custom property binding

Using custom property binding to set the model property of a custom component is a great way for parent and child components to communicate. For example following statement in the parent template shows the binding for the property “childItem” in the child component.

<app-child [childItem]=“parentItem”></app-child> 
  • Here <app-child> is the selector defined in the child component.
  • childItem is a field in the child component.
  • parentItem is a field in parent component.

By using custom property binding here, childItem is bound to the value of the parentItem. But that needs one more thing to be done, using @Input decorator.

Using @Input decorator in custom property binding

By default any property in a component is accessible with in the component where it is defined. If you want to expose any property outside of the component then that property has to be decorated with @Input decorator.

export class UserComponent {
  @Input() usr: User;
  ...
  ...
}

With usr property decorated with @Input decorator, parent component can bind to this property of the child component.

@Input decorator marks a class field as an input property. The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property's value.

Angular custom property binding example

The requirement is to show user details in a child component where each user instance is passed from the parent component.

Creating a User class

Create a Type script class user.model.ts to define a User class. If you are aware of MVC (Model View Controller) pattern then this class is the Model. There are 3 fields name, age and joinDate in the User class.

user.model.ts

export class User {
  name : string;
  age : number;
  joinDate : Date;
  constructor(name: string, age : number, joinDate : Date) {
    this.name = name;
    this.age = age;
    this.joinDate  = joinDate;
  }
}

app.component.ts (Parent component)

import {Component} from '@angular/core';
import { User } from './user/user.model';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users: User[];
  constructor(){
    //Adding User instances to users array
    this.users = [new User('Jack', 56, new Date('2005-03-25')),
    new User('Lisa', 32, new Date('2012-05-09')),
    new User('Jayesh', 28, new Date('2014-10-21'))] ;
  }
}

AppComponent uses User model so that is imported. An array of type User is defined and user instances are added to that array in the Constructor.

app.component.html

<div class="container">
  <h3>User Details</h3>
  <app-user *ngFor="let user of users" 
               [usr]="user">
  </app-user>
</div>

In the template with in the <app-user> selector users array is iterated using ngFor directive and each user instance is bound to the usr property of the child component.

user.component.ts (Child component)

import { 
    Component, Input
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  @Input() usr: User;
}

In the child component usr variable is decorated with @Input decorator indicating that parent component can bind to this property.

User.component.html

In the template user data is displayed using string interpolation.

<div class="container">
  <div class="row">
    <div class="col-xs-6">
      <label>Name: </label> {{ usr.name }}
      <label>Age: </label> {{ usr.age }}
      <label>Join Date: </label> {{ usr.joinDate | date:'dd/MM/yyyy' }}
    </div>
  </div>
</div>
Angular Custom Property Binding

That's all for this topic Angular Custom Property Binding Using @Input Decorator. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Style Binding With Examples
  2. Angular Two-Way Data Binding With Examples
  3. Angular Custom Event Binding Using @Output Decorator
  4. Angular Custom Two-Way Data Binding
  5. How to Install Node.js and NPM in Windows

You may also like-

  1. Angular ngClass Directive With Examples
  2. Angular Cross Component Communication Using Subject Observable
  3. Setting Wild Card Route in Angular
  4. FormArray in Angular With Example
  5. Java Multithreading Interview Questions And Answers
  6. How to Sort HashSet in Java
  7. How to Convert Date And Time Between Different Time-Zones in Java
  8. Convert String to int in Python

Tuesday, July 27, 2021

Angular Class Binding With Examples

In this post we’ll discuss another one-way binding known as Angular class binding. Using class binding you can add and remove CSS classes dynamically from an element's class attribute.

Angular class binding syntax

Syntax of class binding is similar to property binding, square brackets are used for class binding too. To create a class binding, start with the prefix class followed by a dot (.) and the name of the CSS class.

[class.CSS_CLASS]="isRequired"

Here CSS class CSS_CLASS is added when the bound expression is truthy (i.e. isRequired is true), and it removes the class when the expression is falsy (i.e. isRequired is false).

Adding multiple CSS classes

Angular class binding can also be done to multiple classes by using a generic [class] binding without the dot (for example, [class]="classExpr").

The expression can be a space-delimited string of class names. For example

[class]="my-class-1 my-class-2 my-class-3"

You can format it as an object (object, Array, Map, Set, etc) with class names as the keys and truthy/falsy expressions as the values.

As key/value pair- [class]="{my-class-1: true, my-class-2: false}”

As an array - [class]=['my-class-1', 'my-class-2']

Angular class binding examples

1. In the example we display region wise sales figures and want to highlight the sales figures which are good in different color and the sales figures which are not satisfactory in different color. For that styling class binding is used with the condition on the sales figures.

region.model.ts

Model class with fields.

export class Region {
  region : string;
  regionalManager : string;
  sales : number;
  constructor(region: string, regionalManager : string, sales : number) {
    this.region = region;
    this.regionalManager = regionalManager;
    this.sales  = sales;
  }
}

Component class

Component used Region model so that class is imported. There is an array of type Region in which instances of Region are stored.

import { 
    Component
 } from '@angular/core';
import { Region } from './region.model';
@Component({
  selector: 'app-region',
  templateUrl: './region.component.html',
  styleUrls: ['./region.component.css']
})
export class RegionComponent{
  regions: Region[];
  constructor(){
    //Adding Region instances to regions array
    this.regions = [new Region('East', 'Jack', 145),
                   new Region('West', 'Jerry', 225),
                   new Region('North', 'Lisa', 300),
                   new Region('South', 'Randy', 175)] ;
  }
}

CSS Class

.domore {
  background-color: #d41e2e;
  color: #ffffff;
}
.satisfactory {
  background-color:green;
  color: #ffffff;
}

Template

<div class="container">
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>Region</th>
      <th>Manager</th>
      <th>Sales (in millions)</th>
    </tr>
    <tr *ngFor="let region of regions" [class.domore] = "region.sales < 150"
      [class.satisfactory] = "region.sales > 250">
      <td>{{region.region}}</td>
      <td>{{region.regionalManager}}</td>
      <td>{{region.sales}}</td>
    </tr>
  </table>
</div>

With the <tr> element there are two class bindings

 [class.domore] = "region.sales < 150"
 [class.satisfactory] = "region.sales > 250"

When sales is less than 150 domore CSS class is added, when sales is greater than 250 then satisfactory CSS class is added.

class binding example

2. In this example we’ll see how to do class binding for multiple CSS classes. To demonstrate that one more CSS class is added.

CSS

.domore {
  background-color: #d41e2e;
  color: #ffffff;
}
.satisfactory {
  background-color:green;
  color: #ffffff;
}
.brd {
  border: 2px solid black;
}

Component

import { 
  Component
} from '@angular/core';
import { Region } from './region.model';
@Component({
  selector: 'app-region',
  templateUrl: './region.component.html',
  styleUrls: ['./region.component.css']
})
export class RegionComponent{
  regions: Region[];
  constructor(){
  //Adding Region instances to regions array
  this.regions = [new Region('East', 'Jack', 145),
                  new Region('West', 'Jerry', 225),
                  new Region('North', 'Lisa', 300),
                  new Region('South', 'Randy', 175)];
  }

  getCssClasses(sales : Number){
    if(sales < 150){
      return "domore brd";
    }else if(sales > 250){
      return "satisfactory brd";
    }
  }
}

In the component a method getCssClasses() is added in which sales figures are passed as argument. Based on the condition two CSS classes are passed.

Template

<div class="container">
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>Region</th>
      <th>Manager</th>
      <th>Sales (in millions)</th>
    </tr>
    <tr *ngFor="let region of regions" [class] = "getCssClasses(region.sales)">
      <td>{{region.region}}</td>
      <td>{{region.regionalManager}}</td>
      <td>{{region.sales}}</td>
    </tr>
  </table>
</div>

In the <tr> element generic class binding is used with a bound method. From the method, space delimited string of CSS class names is returned.

Angular Class Binding

That's all for this topic Angular Class Binding With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Style Binding With Examples
  2. Angular Attribute Binding With Examples
  3. Angular Custom Event Binding Using @Output Decorator
  4. Angular Custom Two-Way Data Binding
  5. Angular ngClass Directive With Examples

You may also like-

  1. Angular Disable Button Example
  2. Angular @Component Decorator
  3. Angular - Call One Service From Another
  4. How to Add Bootstrap to Angular Application
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. Adding Tomcat Server to Eclipse
  7. Java Reflection API Tutorial
  8. static Reference to The Non-static Method or Field Error

Monday, July 26, 2021

Angular Style Binding With Examples

In this post we’ll discuss another one-way binding known as Angular style binding. Using style binding you can set styles dynamically by getting the value of style property conditionally or through a component's property.


Angular style binding syntax

Syntax of style binding is similar to property binding, square brackets are used for style binding too. To create a style binding, start with the prefix style followed by a dot (.) and the name of the CSS style property.

[style.style-property] = "style-value"

Here style-property which is the binding target will be set to the value of the bound expression, "style-value" in this case.

For example following statement sets the text color of the button based on the value it receives from the buttonColor variable of the component.

<button [style.color]="buttonColor">Submit</button>

Adding unit extension

You can add a unit extension like em, px or % along with CSS style property or with style-value. For example in the following statement font size for the button is set in px unit.

<button class="btn btn-primary" [style.fontSize.px]="fontSize">Submit</button>

Syntax for multiple styles

You can also add multiple style properties. The expression attached to the [style] binding can be passed as a string list of styles like "width: 100px; height: 100px;".

For example- <button [style]="buttonStyle">Submit</button>

Where buttonStyle is a String variable defined in the component as-

buttonStyle : String ='background-color: #4CAF50; font-size:15px; border: none; color: white';

Angular style binding example

In the component there are two properties textFont and textStyle which will be used for setting CSS style properties in the HTML element.

import { 
  Component
} from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  userName : String = "Jack";
  textFont : Number = 25;
  textStyle : String ='background-color: #4CAF50; color: white';
  constructor(){
  
  }
}

Template

<div class="container">
  <div class="row">
    <div class="col-sm-8">
      User name is <span [style.fontSize.px]="textFont" [style]="textStyle">{{userName}}</span> 
    </div>
  </div>
</div>

In the template span element is styled using the style binding. Using [style.fontSize.px] single property is set which also has a unit extension. Using [style]="textStyle" multiple properties are set. Note that font size can also be include with in the multiple properties, done separately here just to demonstrate how to set both single as well as multiple style properties.

Angular Style Binding

Style binding or ngStyle directive

The NgStyle directive can be used as an alternative to direct [style] bindings but as per Angular documentation style binding is preferred.

“However, using the above style binding syntax without NgStyle is preferred because due to improvements in style binding in Angular, NgStyle no longer provides significant value, and might eventually be removed in the future.”

Reference- https://angular.io/guide/template-syntax#style-binding

That's all for this topic Angular Style Binding With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Event Binding With Examples
  2. Angular Class Binding With Examples
  3. Angular Two-Way Data Binding With Examples
  4. Angular Custom Event Binding Using @Output Decorator
  5. Angular ngIf Directive With Examples

You may also like-

  1. Angular @Component Decorator
  2. Angular Example to Render Multiple Rows
  3. Angular Project Structure With File Description
  4. Injector Hierarchy and Service Instances in Angular
  5. Unmodifiable or Immutable Map in Java
  6. Heap Memory Allocation in Java
  7. Spring MVC File Download Example
  8. Constructor in Python - __init__() function

Friday, July 23, 2021

Angular @HostBinding Decorator With Examples

@HostBinding decorator in Angular is used to mark a DOM property of the host element as a binding property. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive. This decorator is quite useful when creating a custom directive as you can bind a property of the host element to a field in your custom directive. By changing the field in the custom directive you can manipulate the host element of the directive.

There is one option that you can pass with the @ HostBinding decorator-

  • hostPropertyName- The DOM property that is bound to a data property.

Thursday, July 22, 2021

Angular Attribute Binding With Examples

In the post Angular Property Data Binding we saw how property binding is done to the corresponding object’s property in the DOM, not to the attribute of the element. Not all HTML element attributes have equivalent properties in the DOM. For such scenario, Angular provides the attribute binding, which sets the value of an attribute on the host element rather than setting the value of the property in the object that represents element in the DOM.

Attribute binding is also type of Angular one-way data binding which is unidirectional. Using attribute binding you can bind data from the component to the view.

Angular One-Way Data Binding

Consider the ARIA and SVG. They are purely attributes, don't correspond to element properties, and don't set element properties. In these cases, there are no property targets to bind to.

<button [attr.aria-label]="buttonAction">{{buttonAction}}</button>

Here ARIA is adding extra label to the button that is only exposed to assistive technology APIs. Anybody using the screen reader will hear the button name as bound to the [attr.aria-label] using Angular attribute binding.

Angular attribute binding example

In the example we’ll use a User model with fields as Name and Age. Let’s take a scenario where you get an array of User objects which you have to display in a table.

You want the colspan attribute of the <td> to be changed as per the length of the user.name. If any of the name’s length is more than 15 then you want colspan to be set to 2 otherwise 1.

user.model.ts

export class User {
  name : string;
  age : number;
  constructor(name: string, age : number) {
    this.name = name;
    this.age = age;
  }
}

user.component.ts

import { 
    Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  users: User[];
  columnSpan = 1;
  constructor(){
    // Initializing User instance
    // Adding user instances in the users array
    this.users = [new User('Jack Ryan', 56),
                  new User('Lisa Ray', 32),
                  new User('Abhinav M', 28)] ;
    this.assignColumenLength();
  }
  // Method to get the colspan value
  assignColumenLength(){
    for(let user of this.users){
      if(user.name.length > 15){
        this.columnSpan = 2;
        break;
      }
    }
  }
}

In the component class User model class is imported and an Array of type User is initialized with some user instances.

In the method assignColumenLength() users array is iterated to check if any of the user name has length more than 15 if yes then columnspan property is set as 2.

user.component.html

<div class="container">
  <h2>User Details</h2>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th [attr.colspan]="columnSpan">Name</th>
      <th>Age</th>
    </tr>
    <tr *ngFor="let user of users">
      <td [attr.colspan]="columnSpan">{{user.name}}</td>
      <td>{{user.age}}</td>
    </tr>
  </table>
</div>

app.component.html

In app.component.html we just need to add the <app-user> tag.

<app-user></app-user>

After running the application if you inspect the element you can see that the colspan attribute has value 1 as no name has length more than 15.

attribute binding

Now change the users array as given below-

this.users = [new User('Jack Ryan', 56),
              new User('Lisa Ray', 32),
              new User('Abhinav Mukhopadyaya', 28)] ;

After running the application if you inspect the element now, you can see that the colspan attribute has value 2 as one of the name has length more than 15.

attribute binding angular

That's all for this topic Angular Attribute Binding With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular One-Way Data Binding Using String Interpolation
  2. Angular Style Binding With Examples
  3. Angular Event Binding With Examples
  4. Angular Class Binding With Examples
  5. Angular Custom Two-Way Data Binding

You may also like-

  1. Angular Reactive Form Example
  2. Angular Disable Button Example
  3. Angular ngFor Directive With Examples
  4. Angular Application Bootstrap Process
  5. Just In Time Compiler (JIT) in Java
  6. Dependency Injection in Spring Framework
  7. Transaction Management in Spring
  8. Installing Anaconda Distribution On Windows

Wednesday, July 21, 2021

Angular Property Binding With Examples

In the post Angular One-Way Data Binding Using String Interpolation we saw one way of data binding. In this article we’ll see how to do Angular property data binding which is also a one-way binding. As the name itself suggests one-way data binding is unidirectional and using property binding you can bind data from the component to the view.

Angular One-Way Data Binding

Property binding in Angular

Angular property binding is used to bind data to a property of an element. Property binding is done using square brackets []

For example- <button [disabled]="false">Submit</button>

Here disabled property of the button is set to false so button will be disabled. Note that binding is done to the disabled property of the button's DOM element, not the attribute.

HTML attribute Vs DOM property

Each HTML element is parsed by the browser and represented as an object in the Document Object Model (DOM). These objects in the DOM, used to represent HTML elements, have properties. Any binding is done to the properties of the DOM element not to the attributes of the HTML element.

It is important to remember that HTML attribute and the DOM property are different things, even when they have the same name. Attributes are defined by HTML. Properties are accessed from DOM (Document Object Model) nodes.

Property binding Angular example

1. In the example we’ll use a User model with fields as Name and Age. Using property binding we’ll bind the “value” property of the input element with user.name.

user.model.ts

export class User {
  name : string;
  age : number;
  constructor(name: string, age : number) {
    this.name = name;
    this.age = age;
  }
}

user.component.ts

import { 
  Component
} from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  user: User;
  constructor(){
    // Initializing User instance
    this.user = new User('Jack', 56);
  }
}

UserComponent uses User model so that is imported. In the Constructor an instance of User is created.

In a real application you may get the User data using http request from some backing application but here it is hard coded.

user.component.html

<div class="form-group m-t-1">
  <label>Name:</label>
  <input class="form-control" [value]="user?.name || 'None'" />
</div>

[value]="user?.name || 'None'" is the property binding part in the template. Uses the safe navigation operator (?.) to protect against null.

app.component.html

In app.component.html we just need to add the <app-user> tag.

<app-user></app-user>

2. In the above example we’ll bind one more property disabled which calls a method to check if user.name has value then return true (which makes disabled=”true”) otherwise return false.

<div class="form-group m-t-1">
  <label>Name:</label>
  <input class="form-control" [disabled]="isValueExist()" [value]="user?.name || 'None'" />
</div>

user.component.ts

import { 
    Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  user: User;
  constructor(){
    // Initializing User instance
    this.user = new User('Jack', 56);
  }

  isValueExist(){
    if (this.user.name === ''){
      return false;
    }else{
      return true;
    }
  }
}

Since user.name has value so the input element is disabled.

Angular Property Data Binding

Now if name is assigned as follows.

this.user = new User('', 56);

Then the isValueExist() method returns false making the property as [disabled]=”false”.

Property Data Binding Angular example

3. This example shows how to disable submit button in an Angular form. Button’s disabled property is bound to the valid property of the form so that the button is enabled only when the form is valid otherwise button is disabled.

<form #userForm="ngForm">
  <div class="form-group">
    <label for="name" class="col-sm-2 col-form-label">Name:</label>
    <div class="col-sm-10">
      <input class="form-control" placeholder="Enter name" id="name" required name="name" [(ngModel)]="user.name">
    </div>
  </div>
  <div class="form-group">
    <label for="age" class="col-sm-2 col-form-label">Age:</label>
    <div class="col-sm-10">
      <input class="form-control" placeholder="Enter age" id="age" required name="age" [(ngModel)]="user.age">
    </div>
  </div>
  <button [disabled]="userForm.invalid" type="submit" class="btn btn-primary">Submit</button>
</form>

With the input element ‘required’ attribute is used to specify that the input is mandatory. Disabled property of the button is bound as given here-

[disabled]="userForm.invalid"

So the button is disabled if form is invalid and it is enabled only when the form is valid.

Both of the values are there so the button is enabled.

disable button angular

One of the value is missing though required so the button is disabled.

disable form submit button

That's all for this topic Angular Property Binding With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Attribute Binding With Examples
  2. Angular Style Binding With Examples
  3. Angular Event Binding With Examples
  4. Angular Class Binding With Examples
  5. Angular Two-Way Data Binding With Examples

You may also like-

  1. Angular @Input and @Output Example
  2. Angular Routing Concepts With Example
  3. Angular ngStyle Directive With Examples
  4. Angular - Call One Service From Another
  5. How to Remove Duplicate Elements From an ArrayList in Java
  6. Java CountDownLatch With Examples
  7. String Slicing in Python
  8. Python Program to Display Armstrong Numbers

Tuesday, July 20, 2021

Angular One-Way Data Binding Using String Interpolation

In this article we’ll see how to do Angular one way data binding using string interpolation. As the name itself suggests Angular one-way binding is unidirectional and using String interpolation you can bind data from the component to the view.

Angular One-Way Data Binding

String interpolation – Angular data binding

The string interpolation binding is specified using pairs of curly braces {{ property/expression }}. The property or expression given in between the curly braces is evaluated and resolved to its value.

String interpolation expression can be:

  • property {{ message }} or {{ user.name }}
  • expression {{7 + (8/4)}}
  • method call {{getData()}}
  • String {{‘Hello ’ + ‘World’}}

Angular String Interpolation One-way data binding example

In the example we’ll use a User model with fields as Name and Age. Using String interpolation binding, values of these fields are displayed in the HTML.

user.model.ts

export class User {
  name : string;
  age : number;
  constructor(name: string, age : number) {
    this.name = name;
    this.age = age;
  }
}

user.component.ts

import { 
    Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  user: User;
  message = 'User Details';
  constructor(){
    console.log('In constructor UserCOmponent');
    this.user = new User('Jack', 56);
  }
}

UserComponent uses User model so that is imported. In the Constructor an instance of User is created. There is also a message property with value assigned to it.

In a real application you may get the User data using http request from some backing application but here it is hard coded.

user.component.html

<div class="container">
  <div class="row">    
    <div class="col-xs-10">
      <h3>{{ message }}</h3>
    </div> 
  </div>
  <div class="row">
    <div class="col-xs-6">
      <label>Name: </label> {{ user.name }}
    </div>
  </div> 
  <div class="row">
    <div class="col-xs-6">
      <label>Age: </label> {{ user.age }}
    </div>
  </div>
</div>

app.component.html

In app.component.html we just need to add the <app-user> tag.

<app-user></app-user>

As you can see here value for message property as well as for user.name and user.age is derived using String interpolation data binding.

One thing to note here is that value you get by String interpolation is always of type String. So user.age which is of type number is internally converted to String.

Angular String Interpolation Binding

Calling a method using Angular One-way data binding

As mentioned above you can also call a method in between the curly braces and also use a String. To demonstrate that let’s remove message property and add a method getMessage() in the component.

export class UserComponent {
  user: User;
  constructor(){
    console.log('In constructor UserCOmponent');
    this.user = new User('Jack', 56);
  }

  getMessage(){
    return 'User Details';
  }
}
And the corresponding changes in the template to get the message by calling method.
<h3>{{ getMessage() }}</h3>

Also notice the <label>{{'Name:'}} </label> showing how you can use String interpolation with String value.

<div class="container">
  <div class="row">    
    <div class="col-xs-10">
      <h3>{{ getMessage() }}</h3>
    </div> 
  </div>
  <div class="row">
    <div class="col-xs-6">
      <label>{{'Name:'}} </label> {{ user.name }}
    </div>
  </div> 
  <div class="row">
    <div class="col-xs-6">
      <label>Age: </label> {{ user.age }}
    </div>
  </div>
</div>

That's all for this topic Angular One-Way Data Binding Using String Interpolation. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Two-Way Data Binding With Examples
  2. Angular Custom Property Binding Using @Input Decorator
  3. Angular Custom Event Binding Using @Output Decorator
  4. Angular Property Binding With Examples
  5. Service in Angular With Examples

You may also like-

  1. Angular Project Structure With File Description
  2. Angular ngClass Directive With Examples
  3. Angular @Input and @Output Example
  4. Angular Disable Button Example
  5. Just In Time Compiler (JIT) in Java
  6. Dependency Injection in Spring Framework
  7. Transaction Management in Spring
  8. Installing Anaconda Distribution On Windows

Monday, July 19, 2021

Java Exception Handling Tutorial

Exception Handling in Java provides a way to handle a situation when an exception is thrown by showing a meaningful message to the user and continue (or terminate) with the flow of the program.

How Java exception handling works

When an exceptional condition occurs with in a method, the method (where the exception occurred) creates an Exception Object and throws it. The created exception object contains information about the error, its type and the state of the program when the error occurred.

The method where the exception is thrown may handle that exception itself or pass it on. In case it passes it on, run time system goes through the method hierarchy that had been called to get to the current method to search for a method that can handle the exception.

If your program is not able to catch any particular exception, that will ultimately be processed by the default handler. The default handler displays a message describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

Type Casting in Java With Conversion Examples

Type casting in Java is used to cast one type (primitive or object) to another type. Whenever you try to assign data of one type to variable of another type, type conversion happens in Java.

Type conversion in Java may be classified into following scenarios.

Out of these four; widening primitive type conversions and widening reference type conversions happen automatically and type casting is not required. Type casting in Java is required in the case of narrowing primitive type conversions and narrowing reference conversions.

Widening primitive conversions

If destination type (type to which you are converting) is larger than the source type, you are widening the type of your source type. This type conversion will happen with out problem and automatically i.e. type casting is not required in this case.

As example-

int i = 10;
float f = i; // Assigning int to float

i which is an int can safely be assigned to float variable as float is compatible with int and also wider than int.

Widening reference conversions

Same way you can have a widening reference conversion. That is applicable in an inheritance scenario where a parent-child relationship exists.

For example if there is a parent class A and a child class B that extends class A then reference type A can safely hold reference type of class B.

A a;
B b = new B();
a = b; // Widening conversion from sub type to super type

Type casting in Java

Though automatic conversion is convenient and helpful, it may not always be possible. Especially in case of narrowing conversions. Again, narrowing conversion can be of two types-

  • Narrowing primitive conversions
  • Narrowing reference conversions

Narrowing primitive conversions

As the name suggests if you try to fit a value into a source that is narrower than the original type of the value then it is a narrowing conversion.

As example– If we do the exact opposite of what we did in the example of widening conversion and try to assign a float value to an int.

int i;
float f = 19.6f;
i = f; // Compile-time error (Type mismatch: cannot convert from float to int)

As you see, you get a compile-time error if you try to assign a float value to an int as it is a narrowing conversion. In case of narrowing conversion you need to explicitly type cast it to make it work.

General form of type casting in Java

(type) value;

Here type is the type to which the value has to be converted.

So in the above example we have to add an explicit cast to int.

Java type casting example

int i;
float f = 19.6f;
i = (int)f;
System.out.println("value " + i); 

Output

value 19

Here you can see that the fractional part is truncated.

Narrowing reference conversions

A super type can hold reference to an object of itself or the sub-types. But doing the opposite, when you want a conversion from super-type to sub-type, you will need type casting.

Since the conversion is from super-type to sub-type it is called narrowing reference conversion.

One important thing to always remember is; an object can only be type cast to its own class or one of its super-type, if you try to cast to any other object you may either get a compile-time error or a class-cast exception (run-time).

Narrowing reference conversion example

If we take the same example as used in widening reference conversion where there is a class A and a child class B that extends class A then reference type A can safely hold reference type of class B. But now we’ll try the opposite too.

A a;
B b = new B()
a = b; // OK widening conversion
b = a; // Compile-time error as it is a narrowing conversion

What you need to do to avoid compile-time error is-

b = (B) a;

Why type casting in Java required

You may have a scenario where child class has methods of its own apart from inheriting methods from the super class or overriding methods of the super class.

Being a good programmer and always trying to achieve polymorphism you will make sure that the reference of the sub-class is held by the super-class object. But one problem is, then you can’t call those methods which are exclusive to sub-class.

In order to call those methods you need casting to the type. Let’s try to understand it with an example.

Type casting Java example code

Here I have a class hierarchy where Payment is an interface and there are two classes CashPayment and CardPayment implementing the Payment interface.

Payment interface

public interface Payment {
 public boolean proceessPayment(double amount);
}

CashPayment class

import org.netjs.examples.interfaces.Payment;

public class CashPayment implements Payment {
 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Cash payment done for Rs. " + amount);
  return true;
 }
}

CardPayment class

import org.netjs.examples.interfaces.Payment;

public class CardPayment implements Payment {

 @Override
 public boolean proceessPayment(double amount) {
  System.out.println("Card Payment done for Rs. " + amount);
  return true;
 }
 
 public void printSlip(){
  System.out.println("Printing slip for payment" );
 }
}

In CardPayment class, note that, there is an extra method printSlip() which is exclusive to this class. Now when you do some payments using the class as given below-

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {
 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
  //int i = 10;
  //float f = i;
  
  int i;
  float f = 19.6f;
  i = (int)f;
  System.out.println("value " + i);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  pd.printSlip();
 }
}

This method call pd.printSlip(); gives following compile-time error as the Payment object has no idea of the printSlip() method, thus the error-

The method printSlip() is undefined for the type Payment

If you want to call printSlip() method you need a cast back to CardPayment class type. Beware that there are two child classes and you don’t need that casting for CashPayment class object. Which means you need to use instanceof operator in conjunction with the casting.

With these corrections the code will now look like-

import org.netjs.examples.interfaces.Payment;

public class PaymentDemo {

 public static void main(String[] args) {
  PaymentDemo pd = new PaymentDemo();
  Payment payment = new CashPayment();
  pd.doPayment(payment, 100);
  payment = new CardPayment();
  pd.doPayment(payment, 300);
  //int i = 10;
  //float f = i;
  
  int i;
  float f = 19.6f;
  i = (int)f;
  System.out.println("value " + i);
 }
 
 public void doPayment(Payment pd, int amt){
  pd.proceessPayment(amt);
  
  if (pd instanceof CardPayment){
   CardPayment cardPay = (CardPayment)pd;
   cardPay.printSlip();
  }
 }
}

Output

Cash payment done for Rs. 100.0
Card Payment done for Rs. 300.0
Printing slip for payment
value 19

Here you can see how instanceof operator is used to make sure that the object is indeed of type CardPayment and then casting is done to the CardPayment type, which makes it possible to call the printSlip() method.

Reference: https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html

That's all for this topic Type Casting in Java With Conversion Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch Case Statement in Java With Examples
  2. Access modifiers in Java
  3. Java pass by value or pass by reference
  4. Array in Java With Examples
  5. Java Exception Handling Tutorial

You may also like-

  1. Abstraction in Java
  2. Object Creation Using new Operator in Java
  3. static Import in Java With Examples
  4. Java Collections Interview Questions And Answers
  5. Java Multithreading Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. How HashMap Works Internally in Java
  8. Race Condition in Java Multi-Threading

Sunday, July 18, 2021

Difference Between sleep And wait in Java Multi-Threading

Difference between sleep() and wait() methods in Java is a popular Java multi-threading interview question. It is another confusing question just like Difference between yield and sleep because functionality wise both sleep() and wait() look quite similar.

When sleep method is called with a specified time, currently executing thread goes in a TIMED_WAITING state.

Same way when wait method is called on an object the thread currently holding the lock on that object goes in a waiting state (or TIMED_WAITING state depending upon which of the three wait methods is being called).

Since both sleep() and wait() methods when called put the currently executing thread in a waiting state then what exactly is the difference between sleep() and wait() methods in Java, that's what we'll try to find here.

sleep() Vs wait() methods in Java multi-threading

  1. The very first difference is that sleep() is defined as a static method in Thread class and operates on the currently executing thread.
    Whereas wait() method is in Object class and operates on the thread which is currently holding the lock on the object on which the wait method is called.
  2. Since wait method is supposed to release the lock on an object so it has to be called from a synchronized context (with in a synchronized method or synchronized block). Not calling wait() method from a synchronized context will result in a IllegalMonitorStateException being thrown.
    With sleep method there is no such mandatory condition. It doesn't need to be called from a synchronized context.
  3. wait() method releases the lock it holds on an object before going to waiting state which gives another thread a chance to enter the synchronized block.
    sleep() method, if called from a synchronized block or method, will not release the lock so another thread won't get a chance to enter the synchronized block.
  4. When wait() method is called upon an object the thread which is currently holding the lock on that object goes to waiting state and it changes state to runnable only when the notify() or notifyAll() method is called by some thread on the same object.

    There are overloaded wait() methods too

       public final void wait(long timeout) throws InterruptedException
       
    And
      public final void wait(long timeout, int nanos) throws InterruptedException
    

    which causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

    In case of sleep() method thread changes state to runnable after the specified time is elapsed. As example Thread.sleep(4000); will make the currently executing thread to sleep for 4 seconds and thread is ready to run again when the specified time has elapsed . This sleep period can be terminated by interrupts.

Example of thread interrupt method

public class InterruptDemo extends Thread {
	@Override
	public void run(){  
		try {
			Thread.sleep(4000);
		} catch (InterruptedException Iexp) {
			System.out.println("Thread Interrupted exception "+ Iexp); 
		}
		 
		System.out.println("thread after interruption...");  
	}  
	public static void main(String[] args) {        
		InterruptDemo thread1 = new InterruptDemo();
		thread1.start();
		thread1.interrupt();
	}
}

Output

Thread Interrupted exception java.lang.InterruptedException: sleep interrupted
thread after interruption...

That's all for this topic Difference Between sleep And wait in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. isAlive() & join() Methods in Java Multi-Threading
  2. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  3. What if run() Method Called Directly Instead of start() Method - Java Multi-Threading
  4. Deadlock in Java Multi-Threading
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Polymorphism in Java
  2. How HashMap Internally Works in Java
  3. Lock Striping in Java Concurrency
  4. Difference Between CountDownLatch And CyclicBarrier in Java
  5. How to Convert Date And Time Between Different Time-Zones in Java
  6. How to Create Immutable Class in Java
  7. Difference Between throw And throws in Java
  8. How to Inject Prototype Scoped Bean in Singleton Bean