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