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.

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

Sunday, July 25, 2021

Angular Event Binding With Examples

In Angular one-way bindings like property binding, attribute binding flow is from Component to template but Angular event binding goes the other direction from template to component. Event binding allows you to listen and respond to certain events such as keystrokes, mouse movements, clicks, and touches sent by the host elements.

Angular event binding

Syntax of Angular event binding

Even binding is denoted by round brackets () and the syntax is as given below.

(event name) = "event handler expression/method"

Angular event binding syntax consists of a target event name within parentheses on the left of an equal sign, and a template statement with in quotes on the right.

For example-

Angular event binding syntax

Here event binding listens for the button's click events, calling the component's onSave() method whenever button is clicked.

Angular Even binding examples

1. First example shows how to disable a button after it is clicked. It uses both property and event binding. A boolean flag is bound to the “disabled” property of the button, when button is clicked using click event a method is called which toggles the boolean flag.

Component (Typescript code)

import { 
  Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  flag : boolean = false;
  // toggle the flag
  onButtonClick(){
    this.flag = !this.flag;
  }
}

Template (HTML file)

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <label for="name" class="col-form-label">Name:</label>
      <input class="form-control" placeholder="Enter name" id="name">        
    </div>
  </div>
  <div class="row mt-3">
    <div class="col-md-12">
      <button class="btn btn-primary" (click)="onButtonClick()" [disabled]="flag">Submit</button>
    </div>
  </div>
</div>

In the button element, click event is bound to a method onButtonClick(). When the button is clicked onButtonClick() method is called on the component which toggles the boolean flag field. Initially value of flag is false thus in the method it becomes true.

2. Binding with input event of input element to get the value of input field.

<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <label for="name" class="col-form-label">Name:</label>
      <input type="text" class="form-control" (input)="updateUserName($event)" id="name">            
    </div>
    <p>{{ userName }}</p>
  </div>
</div>

In the input element, input event is bound to a method updateUserName and $event is passed as an argument. $event denotes the data emitted with the event.

Component

import { 
  Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  userName : String;
  updateUserName(event : Event){
    this.userName = (event.target as HTMLInputElement).value;
  }
}

In the component there is a userName property, value from the passed $event argument is extracted in the method updateUserName() and assigned to the userName.

3. Using the mouseover event to display the selected item. In the example User records are displayed in a table and the user name over which mouse pointer is hovering is displayed in the separate <div> section using the mouseover event.

User Model class

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;
  }
}

Component

import { 
    Component
 } from '@angular/core';
import { User } from './user.model';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  users: User[];
  userName : String;
  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'))] ;
  }
}

Template

<div class="container">
  <div class="bg-warning my-4">
    Selected User: {{userName || '(None)'}}
  </div>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Joining Date</th>
    </tr>
    <tr *ngFor="let user of users">
      <td (mouseover)="userName=user.name">{{user.name}}</td>
      <td>{{user.age}}</td>
      <td>{{user.joinDate | date:'dd/MM/yyyy'}}</td>
    </tr>
  </table>
</div>

In the table (mouseover) event is used with the <td> element.

Build the example and run it, initial display should be as given below.

Angular even binding example

With mouse over selection.

That's all for this topic Angular Event 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 Two-Way Data Binding With Examples
  2. Angular One-Way Data Binding Using String Interpolation
  3. Angular Class Binding With Examples
  4. Angular Custom Property Binding Using @Input Decorator
  5. Angular Custom Event Binding Using @Output Decorator

You may also like-

  1. Angular Example to Render Multiple Rows
  2. Angular Template-Driven Form Validation Example
  3. How to Create a Custom Observable in Angular
  4. Angular ngSwitch Directive With Examples
  5. Shallow Copy And Deep Copy in Java Object Cloning
  6. String Pool in Java
  7. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  8. Spring Boot Hello World Web Application Example

Saturday, July 24, 2021

Angular Two-Way Data Binding With Examples

In this article you will learn how to do two-way data binding in Angular using ngModel directive.

Angular one way data binding provides unidirectional binding either:

From component (Type Script code) to template (HTML view) in the form of String interpolation, property binding.

OR

From template (HTML view) to component (Type Script code) in the form of event binding.

In Angular two way binding both of these one way bindings are combined to create a two-way flow of data between a component class and its template. So, two-way binding does both of these-

  1. If a property in the component is changed that change flows to the view.
  2. Same way change in view is reflected in the bound property in the component.

You can see that the former is property binding where as the latter is event binding and the combination of both results in two-way binding in Angular.

Angular Two-Way Data Binding

Syntax of Angular two-way binding

Syntax for two-way data binding in Angular is [()]. The [()] syntax combines the brackets of property binding, [], with the parentheses of event binding, ().

This syntax for two-way binding is also known as banana in a box.

[( )] = BANANA IN A BOX

It is just a visual way to remember that the parentheses go inside the brackets.

How to use two-way binding in Angular

In Angular ngModel directive is used for two-way bindings. It simplifies creating two-way data bindings on form elements like input element.

[(ngModel)] = "[PROPERTY_IN_COMPONENT]"  

For example: <input type="text" [(ngModel)]="userName" />

If userName property in the component has an initial value that is shown as the value of the input. Also any change in the value done by the user in the view changes the bound property value in the component too.

For using the ngModel directive in a two-way data binding, you must do these two things-

  • Import the FormsModule
  • Add it to the NgModule's imports list
import { FormsModule } from '@angular/forms';
..
..
@NgModule({
  ..
  ..

  imports: [
    BrowserModule,
    FormsModule
  ],
  ..
  ..
})
export class AppModule { }

You could achieve the same result with separate bindings to the <input> element's value property and input event:

<input [value]="userName" (input)="userName=$event.target.value">

or like this-

<input [ngModel]="userName" (ngModelChange)="userName=$event">

Using [(ngModel)] simplifies the two-way data binding with a shorter syntax. Note that, this [(ngModel)] syntax can only set a data-bound property. If you need to do something more, you can write the expanded form as shown above. For example, the following changes the <input> value to uppercase:

<input [ngModel]="userName" (ngModelChange)="setUppercaseName($event)">

Angular two-way binding example

1. Here is an example with a single property userName in the component.

import { 
  Component
 } from '@angular/core';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent {
  userName = "Rita";
  constructor(){}  
}

Template

<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <div class="form-group">
          <label for="username">User Name:</label>
          <input class="form-control" [(ngModel)]="userName">
          <p>{{ userName }}</p>
      </div>
    </div>
  </div>
</div>

In the template as you can see target of two-way binding is ngModel directive and the expression is the property “userName” property of the component.

On running the example you get the output as-

angular twoway data binding example

Since property “userName” has an initial value so that value is displayed in the template.

Now if you change that value in the input element, that changed value would be reflected in the component too. Using String interpolation that value is fetched from the component and shown below the input element.

2. Two-way binding with fields of a model can be done in a similar way. Let’s say there is a Model class User with 2 fields name and age.

user.model.ts

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

user.component.ts

In the component instance of the Model class User is crated and initialized with values.

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 Ryan', 56);
  }
}

user.component.html

<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <div class="form-group">
        <label for="username">User Name:</label>
        <input class="form-control" [(ngModel)]="user.name" id="username">
        <p>{{ user.name }}</p>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-6">
      <div class="form-group">
        <label for="username">Age:</label>
        <input class="form-control" id="age" [(ngModel)]="user.age">
        <p>{{ user.age }}</p>
      </div>
    </div>
  </div>
</div>

That's all for this topic Angular Two-Way Data 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 Custom Two-Way Data Binding
  2. Angular Attribute Binding With Examples
  3. Angular @Input and @Output Example
  4. Angular ngIf Directive With Examples
  5. Angular ngClass Directive With Examples

You may also like-

  1. Injector Hierarchy and Service Instances in Angular
  2. What is Client Side Routing in Angular
  3. Checkbox in Angular Form Example
  4. How to Setup Angular
  5. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  6. Serialization and Deserialization in Java
  7. Reading Delimited File in Java Using Scanner
  8. Bubble Sort Program in Python

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