Showing posts with label Angular Directives. Show all posts
Showing posts with label Angular Directives. Show all posts

Wednesday, January 10, 2024

Angular ngClass Directive With Examples

Using Angular ngClass directive you can dynamically add or remove CSS classes for a DOM element.

With ngClass the CSS classes can be provided in one of the following ways-

  1. string- The CSS classes listed in the string (space delimited) are added.
     <some-element [ngClass]="'first second'">...</some-element>
    
  2. Array- The CSS classes declared as Array elements are added.
    <some-element [ngClass]="['first', 'second']">...</some-element>
    
  3. Object- As a key, value pair where keys are CSS classes and values are conditions. CSS classes get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.
    <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
    

Angular ngClass directive example

Here is a simple example showing usage of ngClass. First add a CSS class.

app.component.css

.text-border {
  color: white;
  border: 1px dashed black;
  background-color: blue;
}

Then in the template you can add <div> elements, one with value as true (so that CSS class is added) and one with value as false (so that CSS class is removed).

<div class="container">
  <div [ngClass]="{'text-border': false}">
    This text has no border
  </div>
  <div [ngClass]="{'text-border': true}">
    This text has border
  </div>
</div>
ngClass Directive

But you will see the real power of ngClass, just like with ngStyle directive, when the CSS class assignment happens dynamically.

Angular ngClass directive dynamic class assignment

In this example we’ll simulate a message for network transfer. There is a button “show status” that shows the current status of the network transfer. After few clicks if network transfer is still not done message is displayed in red color.

CSS used

.text-border {
  color: white;
  border: 1px dashed black;
  background-color: red;
}

Component class

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  temp = [];
  onButtonClick(){
    this.temp.push('Still transferring packet');
  }
}

Whenever button is clicked on the UI, onButtonClick() function is called which adds one more message to the array.

Template

<div class="container">
  <button class="btn btn-primary" (click)="onButtonClick()">
    Show Status
  </button>
  <div *ngFor="let t of temp; let i = index">
    <span [ngClass]="{'text-border' : i > 5}">{{t}}</span>
  </div>
</div>

In the template ngFor directive is used to iterate through the array of messages. Using ngClass directive CSS class ‘text-border’ is added dynamically when the iteration index is greater than 5.

Angular ngClass Directive

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


Related Topics

  1. Angular ngSwitch Directive With Examples
  2. Angular ngStyle Directive With Examples
  3. Angular ngIf Directive With Examples
  4. Angular @Component Decorator
  5. How to Install Node.js and NPM in Windows

You may also like-

  1. Angular First App - Hello world Example
  2. Passing Query Parameters in Angular Routing
  3. How to Create a Custom Observable in Angular
  4. Radio Button in Angular Form Example
  5. Unmodifiable or Immutable List in Java
  6. Initializer Block in Java
  7. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  8. Python Program to Display Armstrong Numbers

Friday, June 16, 2023

How to Use ngFor and ngIf in Same Element in Angular

In Angular if you want to use two structural directives like *ngFor and *ngIf in the same element (like <div>, <tr>) that results in an error.

Can't have multiple template bindings on one element. Use only one attribute prefixed with *

How to use ngFor and ngIf on same element

It is very common to show only specific records while looping i.e. having ngIf to test a condition with in a ngFor loop or to loop elements only when a condition is true i.e. having ngFor within ngIf condition.

For example let’s say you have to iterate through Region objects using ngFor showing only those records where sales is greater than 200, writing it as given below results in error as both *ngFor and *ngIf are with in the same <tr> element.

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

Wednesday, June 14, 2023

Angular ngIf Directive With Examples

Angular provides some of the built-in directives to perform the most common tasks in web application development. Angular ngIf directive is used to conditionally include or remove an element in the HTML document.

If the expression used with the ngIf directive evaluates to true, element is included in the DOM if expression evaluates to false then the element is removed from the DOM.

Here are some examples of ngIf directive-

1. <div *ngIf="true"></div>

Element is always displayed.

2. <div *ngIf="false"></div>

Element is never displayed.

3. <div *ngIf="x > y"></div>

Element is displayed if x is greater than y.

4. <div *ngIf="myFunc()"></div>

Element is displayed if myFunc returns true.


ngIf is a structural directive

As you would have seen in the above examples, asterisk (*) precedes the ngIf directive attribute which means it is a structural directive. Structural directives are responsible for HTML layout. They change the DOM's structure, typically by adding, removing, or manipulating elements.

Internally Angular translates the *ngIf attribute into a <ng-template> element. If you have a statement as given below

<div *ngIf="user" class="name">{{user.name}}</div>

It is translated into a <ng-template> element, wrapped around the host element, like this.

<ng-template [ngIf]="user">
  <div class="name">{{user.name}}</div>
</ng-template>

Tuesday, August 3, 2021

ng-template in Angular

In this tutorial we’ll learn in detail about <ng-template> element in Angular.


Using ng-template

Using <ng-template> element in Angular you can define a template that doesn't render anything by default. Here note that it "only defines a template". That gives you control over how the content is displayed.

For example if you just wrap some elements in an <ng-template> without using any structural directive or some other way to display those wrapped elements, those elements disappear.

<p>Using ng-template here</p>
<ng-template>
    <p>This text is not displayed</p>
</ng-template>

The above code will display only-

Using ng-template here

<p> element wrapped within <ng-template> is not displayed.

Now we’ll see how <ng-template> is already used by many built-in structural directives in Angular. We’ll also see how to use <ng-template> in conjunction with ngTemplateOutlet and with TemplateRef to render the wrapped elements.

Friday, July 16, 2021

Angular ngStyle Directive With Examples

Using Angular ngStyle directive you can set the CSS properties for the containing HTML element. Style properties are specified as colon-separated key-value pairs. The key is a style name, with an optional .<unit> suffix (such as 'top.px', 'font-style.em'). The value is an expression to be evaluated.

For example-

Here font-style, color and background-color CSS properties are set for the containing div element using ngStyle.

<div class="container">
  <div [ngStyle]="{'font-style':'italic', color:'white', 'background-color':'blue'}">
    Text styled using ngStyle
  </div>
</div>

Using ngStyle directive dynamically

The real benefit of using ngStyle is when the value is dynamic. The values that you assign to ngStyle can be an expression and the result of that expression is assigned as the value of the CSS property. Here is an example to show that.

In the example there is a Model class Student with 3 marks fields and the color of the mark is changed as per the conditions which are defined with in a function in TypeScript file.

Wednesday, July 14, 2021

NgNonBindable Directive in Angular

In this article we'll see how to use the NgNonBindable directive.

Generally if you use any binding or directive with any element it is evaluated to the expression and render that evaluated expression. For example if you have a component to show user name-

non-bindable.component.ts

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

@Component({
    selector: 'non-bindable',
    templateUrl: './non-bindable.component.html',
})
export class NonBindableComponent{
    userName:String = 'TestUser'
}

non-bindable.component.html

<p>Hello {{ userName }}</p>

After compiling this code and running it you would see that the String interpolation {{ userName }} is evaluated to the assigned value and that’s what is rendered.

Wednesday, July 7, 2021

How to Create a Custom Structural Directive in Angular

In this article we’ll see how to create a custom structural directive in Angular. Structural directive is used to modify DOM structure by adding or removing DOM elements.

In order to create a structural directive in Angular you should be clear about how the structural directives internally work so here is a small section on that.

The asterisk, *, syntax on a structural directive, such as *ngIf, is shorthand that Angular interprets into a longer form. Angular transforms the asterisk in front of a structural directive into an <ng-template> that surrounds the host element. For example

<div *ngIf="user" class="name">{{user.name}}</div>

is translated into a <ng-template> element, wrapped around the host element, like this.

<ng-template [ngIf]="user">
  <div class="name">{{user.name}}</div>
</ng-template>

Same way for *ngFor

<div *ngFor="let item of items">
    {{item .name}}
</div>

Above statement is internally expanded into a long form that uses the ngForOf selector on an <ng-template> element. Repeat the <ng-template> for each item in the list

<ng-template ngFor let-item [ngForOf]="items">
  <div>{{item.name}}</div>
</ng-template>

Monday, July 5, 2021

How to Create a Custom Attribute Directive in Angular

In this article we’ll see how to create a custom attribute directive in Angular. Attribute directive is used to modify the appearance or behavior of DOM element.

Angular provides a class named ElementRef which is a wrapper class around a native element inside of a View so it can access DOM. Permitting direct access to the DOM can make your application more vulnerable to XSS (Cross-Site Scripting) attacks. It is recommended to create a custom directive and use ElementRef class inside it to change the appearance or behavior of DOM element.

In Angular there is also a Renderer2 class that helps in implementing custom rendering. So in our custom attribute directive we'll make use of the Renderer2 and ElementRef classes to manipulate elements.


Thursday, July 1, 2021

Directives in Angular

Angular directives are classes that add additional behavior to elements in your Angular applications. Using directives you can change the appearance or behavior of an element, change the DOM layout by adding and removing DOM elements.

Types of directives in Angular

There are three different types of Angular directives-

1. Components— Yes even components are directives only difference with other directives is that components are a directive with a template.

2. Attribute directives— Attribute directives are used to change the appearance or behavior of an element, component, or another directive.

3. Structural directives— Structural directives are used to change the DOM layout. These directives can add and remove DOM elements from the DOM structure.

types of angular directives

Wednesday, June 30, 2021

Angular ngSwitch Directive With Examples

In the post Angular ngIf Directive With Examples we saw how to use ngIf directive but you may have a scenario where you need to render different elements based on different conditions. In such scenario you can use Angular ngSwitch directive rather than using ngIf several times.

Angular ngSwitch directive

The [ngSwitch] directive on a container specifies an expression to match against. The expressions to match are provided by ngSwitchCase directives on views within the container.

Syntax of Angular ngSwitch

<container-element [ngSwitch]="switch_expression">
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
  <some-element *ngSwitchCase="match_expression_2">...</some-element>
  ...
  <some-element *ngSwitchDefault>...</some-element>
</container-element>
  1. Every view that matches is rendered.
  2. If there are no matches, a view with the ngSwitchDefault directive is rendered.
  3. ngSwitchDefault element is optional. If you don't use it, nothing will be rendered when there is no matching value.
  4. Note that asterisk (*) precedes the ngSwitchCase which means it is a structural directive and used to add or remove DOM element.
  5. If the value of the match_expression matches the value of the switch_expression, the corresponding element is added to the DOM. If the expression doesn’t match, then the element is excluded from the DOM.
  6. The element that the ngSwitch directive is applied to is always included in the HTML document, ngSwitch is specified within square brackets.

Tuesday, June 29, 2021

Angular ngFor Directive With Examples

Angular ngFor directive is the looping directive in Angular that iterates over each item in the collection and renders the element (or section of elements) for each item.

Here is an example where ngFor is contained in an <li> element.

<li *ngFor="let item of items>
  ..
  ..
</li>

Note that ngFor is the shorthand form which is internally expanded into a long form that uses the ngForOf selector on an <ng-template> element.

<ng-template ngFor let-item [ngForOf]="items">
  <li>...</li>
</ng-template>

Note that asterisk (*) precedes the ngFor which means it is a structural directive and used to add or remove DOM element.