Home » Framework » Angular » ngClass ngStyle ngModel directives of Angular Application

ngClass ngStyle ngModel directives of Angular Application

This article explains the directives, types of directives, and the most common use of built-in attribute directives like ngClass, ngStyle, and ngModel in the Angular Application.

Directives are classes that add extra behavior to the elements or components in Angular Application. There are different types of directives available in angular applications.

The types of directives are

  1. Components.
  2. Attribute Directives
  3. Structural Directives.

Components

Components are the directives with the template. This is the most common directive of angular application. We have already seen the components in detail in the last article. If you want to know more please take a look at Angular Components and Its usages.

If you don't have any idea about working with components then please go through that first with the above link. Because here many places I am dealing with components to explain directives.

Attribute Directives

Attribute Directives are the directives that change the appearance of an element, component, or other directives. Not only the appearance it can change the behavior too.

Structural Directives

Structural Directives are the directives that change the layout of DOM with the help of adding or removing the elements of DOM.

By default Angular Application is having some built-in directives of Attributes Directives as well as Structural Directives. Here let us see the most common types of built-in directives from Attubues and Structural.

Built-in Attribute Directives

Attribute Directives are classes that add extra behavior and change the appearance of an element, component, or other directives. Here let us see some most common use of Built-in Attribute Directives that are

  1. NgClass
  2. NgStyle
  3. NgModel

First, let us create a new angular application to see the examples of Built-in Attribute Directives. Type the below command to create the new angular application.

ng new angular-directive

The above command creates the new Angular Application in the chosen location named 'angular-directive'. Now the application is ready. Let us see the examples one by one.

NgClass Directive

NgClass is a built-in attribute directive that adds or removes CSS classes to change the appearance of elements or components. Let us see the example below.

First, let us create a component to see the examples of NgClass by using the below command.

ng g c ngclass

The above command creates the component named 'ngclass' under the app folder. Now let us create some examples of NgClass within the component before that we have to know the different types of using NgClass directive.

string - The CSS classes are declared as strings in the ngClass directive. We can use multiple CSS classes with the space.

Array - The CSS classes are declared as an array of elements in the ngClass directive.

Object - The CSS classes are added when the condition is true otherwise they are removed.

Now let's do the below changes in the 'ngclass' component to see all the types of using ngClass directive.

Open the ngclass.component.html under the ngclass folder and replace it with the below code.

<h2>NgClass Example</h2>
<h3 >Student Mark List</h3>
<table>
  <thead>
    <th>Name</th>
    <th>Score</th>
    <th>Result</th>
  </thead>
  <tr *ngFor="let student of studentList">  
    <td>{{student.name}}</td> 
    <td>{{student.score}}</td>    
    <td>{{student.result}}</td>
  </tr>
</table>

Open the ngclass.component.ts file and replace it with the below code.

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ngclass',
  templateUrl: './ngclass.component.html',
  styleUrls: ['./ngclass.component.css']
})
export class NgclassComponent implements OnInit {
  constructor() { }
  studentList:Array<any> =[
    {"name":"John", "score":35, "result":"PASS"},
    {"name":"Peter", "score":20, "result":"FAIL"},
    {"name":"David", "score":15, "result":"FAIL"},
    {"name":"Salman", "score":45, "result":"PASS"},
    {"name":"Khan", "score":80, "result":"PASS"}
  ];
  ngOnInit(): void {
  }
}

Open the ngclass.component.css file and replace it with the below code.

.font-bold{
    font-weight: bolder;
}
.name{
    color:blue;
}
.score{
    color:purple;
}
.pass{
    color:green;
   
}
.fail{
    color:red;
    font-weight: bolder;
}

The above changes display the student mark list in the table format. To see the result in the browser do the changes in the app.component.html file like below.

Open the app.component.html file and replace it with the below code.

<h1 style="color:green;text-align: center;">Welcome to TipsToCode!</h1>
<h1>Built-in Attribute Directives</h1>
<app-ngclass></app-ngclass> 

Now save all the changes and run the application using the ng serve command. Open the URL http://localhost:4200 in the browser and you can see the result like below.

angular-directives
angular-directive-examples

Now we have to apply the CSS classes written in ngclass.component.css to the student mark list table written in the ngclass.component.html file.

Add the ngClass directive with string type in the Name column of the table like below.

<td [ngClass]="'name font-bold'">{{student.name}}</td>

The above directive applies the two CSS classes 'name' and 'font-bold' to the Name column of the table. These two CSS styles we already added in the ngclass.component.css file. It displays the student name as blue color with bolder. Save the change and run the application again to see the result.

Add the ngClass directive with the type Array of elements in the Score column of the table like below.

<td [ngClass]="['score', 'font-bold']">{{student.score}}</td>

The above ngClass directive adds the two CSS classes 'score' and 'font-bold' to the Score column of the table. It displays the score column as purple color with bolder.

Now let us see the Object type of ngClass directive. For that, we have to write the logic like if the score is greater than on equal to 35 then it applies the green color to the result column of the table else it applies the red color.

There are many ways to achieve this.

Format 1

<td [ngClass]="{'pass': student.score>=35,'fail': student.score<35}">{{student.result}}</td>

The above code applies the green color to the values of result column when the score is greater than or equal to 35 else it applies red color.

Format 2

<td [ngClass]="student.score>=35 ? 'pass font-bold' : 'fail'">{{student.result}}</td>

The above code applies the two CSS classes 'pass' and 'font-bold' to the values of result coulmn when the score is greater than or equal to 35 else it applies the CSS class 'fail'.

The below code of ngclass.component.html shows all the examples of the ngClass directive.

<h2>NgClass Example</h2>
<h3 >Student Mark List</h3>
<table>
  <thead>
    <th>Name</th>
    <th>Score</th>
    <th>Result</th>
  </thead>
  <tr *ngFor="let student of studentList">  
    <td [ngClass]="'name font-bold'">{{student.name}}</td> 
    <td [ngClass]="['score', 'font-bold']">{{student.score}}</td>    
    <!-- <td [ngClass]="{'pass': student.score>=35,'fail': student.score<35}">{{student.result}}</td> -->
    <td [ngClass]="student.score>=35 ? 'pass font-bold' : 'fail'">{{student.result}}</td>
  </tr>
</table>

Now save the changes and run the application again to see the below result in the browser.

Angular ngClass Directive
Angular ngClass Directive

NgStyle Directive

NgStyle is a built-in attribute directive that adds inlines styles to the elements in the Angular Application. There are many ways to use NgStyle attribute to the elements. Let's see all the ways of using NgStyle by creating the new component in the application.

ng g c ngstyle

The above command creates the component under the app folder named 'ngstyle'. Let see the examples of NgStyle attribute in this component's template.

Open the ngstyle.component.html file and replace it with the below code

<h2>NgStyle Example</h2>
<h3>Student Mark List</h3>
<table >
  <thead >
    <th>Student Name</th>
    <th>Score</th>
    <th>Result</th>
  </thead>
  <tr *ngFor="let student of studentList">  
    <td>{{student.name}}</td> 
    <td>{{student.score}}</td>
    <td>{{student.result}}</td>
  </tr>
</table>

Replace the below code in the ngstyle.component.ts file

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ngstyle',
  templateUrl: './ngstyle.component.html',
  styleUrls: ['./ngstyle.component.css']
})
export class NgstyleComponent implements OnInit {
  constructor() { } 
  passStyle = 'green';
  failStyle = 'red'; 
  passStyles = {
      'font-style':'italic',
      'font-weight': 'bold',
      'font-size': '16px',
      'color':'green'
  };
  failStyles = {
    'font-style':'normal',
      'font-weight': 'normal',
      'font-size': '16px',
      'color':'red'
  };
  headStyle = {'font-weight':'800', 'color':'orange', 'background-color':'yellow'};  
  studentList:Array<any> =[
    {"name":"John", "score":35, "result":"PASS"},
    {"name":"Peter", "score":20, "result":"FAIL"},
    {"name":"David", "score":15, "result":"FAIL"},
    {"name":"Salman", "score":45, "result":"PASS"},
    {"name":"Khan", "score":80, "result":"PASS"}
  ];  
  ngOnInit(): void {  
  }
}

Let's put the ngclass component directive name in the app.component.html file like below to see the result on the main page of the angular application.

Replace the below code in the app.component.html file

<h1 style="color:green;text-align: center;">Welcome to TipsToCode!</h1>
<h1>Built-in Attribute Directives</h1><
<app-ngstyle></app-ngstyle>

Save the changes and run the application. Open this URL http://localhost:4200 in the browser it displays the student mark list. Let's apply the inline styles to the mark list table written in the ngstyle.component.html file

<td [ngStyle]="{'color':'blue'}">{{student.name}}</td>

The above ngStyle directive applies the inline style 'color' to the name column of the table. It displays the names in blue color in the name column. We can add multiple inline styles with commas like below.

<td [ngStyle]="{'color':'blue', 'font-weight':'bolder'}">{{student.name}}</td>

The above ngStyle directive adds multiple inline styles to the name column. It displays the names in blue color with a bolder format.

If we want to add the CSS style 'font-size' then we need to mention the size of the font as pixel(.px) or ems(.em) or percentage(%). Normally the CSS style 'font-size:24px;' displays the font with the size of 24px. But in the ngStyle directive, we can't write it as the normal way I mean the below code won't work.

[ngStyle]="{'font-size':24px;}"

Instead of the above code, we have to write the below code to make it work.

[ngStyle]="{'font-size.px':24}" (or) [ngStyle]="{'font-size.em':1.5}" (or) [ngStyle]="{'font-size.%':100}"

Now we can apply this style to the score column of the table like below.

<td [ngStyle]="{'font-size.em':1.5}">{{student.score}}</td>

The abvoe code displays the values of score column with the font size of 1.5em.

Now we have to apply the inline CSS styles with ngStyle attribute based on the logic. For example, we have to add the inline style 'color:green;' to the result column of the table if the score is greater than or equal to 35 else it adds 'color:red;'

<td [ngStyle]="{'color': student.score>=35 ? 'green' : 'red'}">{{student.result}}</td>

The above code applies the green color to the result column of the table if the score is greater than or equal to 35 else it applies red color to that. If you want to add multiple inline styles then add the styles with comma seperated like below.

<td [ngStyle]="{'color': student.score>=35 ? 'green' : 'red','font-weight': student.score>=35 ? 'bolder' : 'bold'}">{{student.result}}</td>

We can apply the inline styles that declared in the ngstyle.component.ts file like below.

<td [ngStyle]="{'color': student.score>=35 ? passStyle : failStyle}">{{student.result}}</td>

In the above code inline styles are declared with the variables passStyle and failStyle in the ngstyle.component.ts file.

We can declare the multiple inline styles in the typescript file like below.

<td [ngStyle]="passStyles">{{student.result}}</td>

Look at the passStyles object that declared in the ngstyle.component.ts file.

The below code of the ngstyle.component.html file is having all the examples of ngStyle directive.

<h2>NgStyle Example</h2>
<h3>Student Mark List</h3>
<table >
  <thead >
    <th>Student Name</th>
    <th>Score</th>
    <th>Result</th>
  </thead>
  <tr *ngFor="let student of studentList">  
    <td [ngStyle]="{'color':'blue', 'font-weight':'bolder'}">{{student.name}}</td> 
    <td [ngStyle]="{'font-size.em':1.5}" [style.color]="'green'">{{student.score}}</td>
    <!-- <td  [ngStyle]="{'color': student.score>=35 ? 'green' : 'red'}">{{student.result}}</td> -->
    <!-- <td  [ngStyle]="{'color': student.score>=35 ? 'green' : 'red','font-weight': student.score>=35 ? 'bolder' : 'bold'}">{{student.result}}</td> -->
    <td  [ngStyle]="{'color': student.score>=35 ? passStyle : failStyle}">{{student.result}}</td>
    <!-- <td [ngStyle]="passStyles">{{student.result}}</td> -->
    <!--<td [ngStyle]="failStyles">{{student.result}}</td> -->
  </tr>
</table>

NgModel Directive

NgModel is a built-in attribute directive that displays the data property and updates that property when the changes happen.

We can use this 'NgModel' directive in the input text box of forms. For that, we need to import the forms module in the app.module.ts file like below.

import { FormsModule } from '@angular/forms';
imports: [
    FormsModule
  ],

Now let's create a new component to see all the examples of NgModel directive.

ng g c ngmodel

The above command creates the component under the app folder named 'ngmodel'. Open the ngmodel.component.html file and replace it with the below code.

<h2>NgModel Examples</h2>
<div>
    <label>HTML Div</label>
    {{name}}
</div>
<div>
  <label>Without NgModel</label>
  <input [value]="name" (input)="name" id="without-ngModel">
</div>
<div>
  <label>With NgModel one way binding</label>
  <input [ngModel]="name" id="with-ngModel">
</div>
<div>
    <label>With NgModel two way binding</label>
    <input [(ngModel)]="name" id="with-ngModel">
  </div>
<div>
  <label>Bindon NgModel</label>
  <input bindon-ngModel="name" id="bindon-ngModel">
</div>
<div>
  <label>NgModel with NgModelChange</label>
  <input [ngModel]="name" (ngModelChange)="name = $event.toUpperCase()" id="ngModel-with-ngModelChange">
</div>

Replace the below code in the ngmodel.component.ts file.

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ngmodel',
  templateUrl: './ngmodel.component.html',
  styleUrls: ['./ngmodel.component.css']
})
export class NgmodelComponent implements OnInit {
  constructor() { }  
  name = 'tipstocode';
  ngOnInit(): void {
  }
}

Now put this component directive name in the app.component.html file

<h1 style="color:green;text-align: center;">Welcome to TipsToCode!</h1>
<h1>Built-in Attribute Directives</h1>
<app-ngmodel></app-ngmodel>

Save the change and run the application again. You can see the below result in the browser.

Angular ngModel Directive
Angular ngModel Directive

It displays the below things in the browser.

  1. HTML div element binds the value.
  2. Input text box without ngModel directive.
  3. Input text box with one way binding of ngModel directive like [ngModel].
  4. Input text box with two way binding of ngModel directive like [(ngModel)].
  5. Input text box with bindon-ngModel directive.
  6. Input text box with property binding of ngModel directive and event binding of ngModelChange

Now change the value of the text box that has without ngModel directive. It changes the value of only that text box, not others. The same thing happens when changing the value of the text box that has a one-way binding of ngModel directive like [ngModel].

Change the value from any of these input text boxes that have a two-way binding of ngModel directive like [(ngModel)] or bindon-ngModel or [ngModel] with (ngModelChange). It updates all the input text boxes and HTML div.

If we change the value of the input text box that has [ngModel] with (ngModelChange) directives then it updates the value of all the input text boxes and HTML div with the uppercase format.

Due to the two-way binding of the ngModel directive, it displays the data and updates the data when changes happen. Now let's see some brief information on two-way data binding.

Two-way data binding display the data property and update that property when changes happen. We can do this binding in Component elements as well as HTML elements. Two-way data binding combined with property binding and event binding.

The syntax for two-way data binding is [( )] or bindon- keyword.

The syntax for property binding is [ ] or bind- keyword and the syntax for event binding is ( ) or on- keyword. These binding are called one-way data binding.

Now coming to an example all the input text boxes display the data declared in the ngmodel.compoent.ts file like below.

name = 'tipstocde';

Two-way binding of ngModel directive like [(ngModel)]="name" in text box display the value of the 'name' variable and updates the value to the 'name' variable when changes happen. That's why it updates the value in all the input text boxes and the HTML div in the example.

I hope you understood directives, types of directives, and the most common use of built-in attribute directives like ngClass, ngStyle, and ngModel. In the next article, we will see detailed information on built-in structural directives. Thanks!. Keep Reading!.

Leave a Reply

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