Wednesday, October 18, 2023

Attribute Directive Part 2-->Angular ngClass Directive Example

It is used to add or remove CSS classes dynamically (run-time) from a DOM Element.

  1. ngClass with string
  2. ngClass with array
  3. The ngClass with object
  4. ngClass with component method
Example
.ts changes

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

@Component({
  selector: 'app-attributestylebinding',
  templateUrl: './attributestylebinding.component.html',
  styleUrls: ['./attributestylebinding.component.css']
})
export class AttributestylebindingComponent {

  a:number=0;
  b:number=0;
  res:number=0;
  cssclassname:string="default";
 sum()
 {
   this.res=this.a+this.b;
   this.cssclassname="c1";
 }
 mult()
 {
   this.res=this.a*this.b;
   this.cssclassname="c2";
 }
}


.html Changes

<style>
    .default{
        visibility: hidden;
    }
    .c1{
        color: blue;
        visibility: visible;
    }
    .c2{
        color: maroon;
        visibility: visible;
    }
   </style>
<div style="font-size:x-large;margin:20px">
enter a:<input type="number" [(ngModel)]="a"> <br>
enter b:<input type="number" [(ngModel)]="b"> <br>
<input type="button" value="sum" (click)="sum()">
<input type="button" value="mult" (click)="mult()">
<br>
<h3 [ngClass]="cssclassname">result:{{res}}</h3>
</div>


Output



















ng Class as a string

Example

.html Changes
























.ts Changes

























Output



















Applying multiple css classes with ngClass Directive:

.html Changes

<h3 [ngClass]="'one four'">Class Binding</h3>

Output



















note:
-----
*ngClass directive is deprecated with Angular4,the alternative is class directive
         
                   ...
  <h3 [class]="cssclassname">result:{{res}}</h3>

Example

.ts

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

@Component({
  selector: 'app-attributestylebinding',
  templateUrl: './attributestylebinding.component.html',
  styleUrls: ['./attributestylebinding.component.css']
})
export class AttributestylebindingComponent {

  a:number=0;
  b:number=0;
  res:number=0;
  cssclassname:string="default";
 sum()
 {
   this.res=this.a+this.b;
   this.cssclassname="c1";
 }
 mult()
 {
   this.res=this.a*this.b;
   this.cssclassname="c2";
 }
}


.html changes

<style>
.one{ color: red; }
.two{ font-size: 30px; }
.three{ font-weight: bold; }
.four{ font-style: italic; }
.five{ color: green; }
.default{ visibility: hidden; }
 .c1{
     color: blue;
     visibility: visible;
 }
 .c2{
     color: maroon;
     visibility: visible;
 }
</style>
<h3 [ngClass]="['three', 'four', 'five']">Class Binding</h3>  
<div style="font-size:x-large;margin:20px">
enter a:<input type="number" [(ngModel)]="a"> <br>
enter b:<input type="number" [(ngModel)]="b"> <br>
<input type="button" value="sum" (click)="sum()">
<input type="button" value="mult" (click)="mult()">
<br>
<h3 [class]="cssclassname">result:{{res}}</h3>
</div>

Output




Example 2:

Note:
class directive allows applying CSS class based on Boolean type, where as it is
 not supported by ngclass directive
 syntax:
    <tagname [class.cssclassname]="true|false">..</tagname>

          true-it will apply CSS class to html element
          false-it will remove CSS class from html element








.html 

<style>
    .c1{
        background-color: black;
        color:white;
        border:5px solid yellow;
        width:30%;
        padding: 10px;
        margin: 20px;
    }
</style>
<h2 [class.c1]="flag">Rajakonda Uday Kumar</h2>
<br>
<input type="checkbox" [(ngModel)]="flag">Apply CSS

.ts

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

@Component({
  selector: 'app-classbindingexample',
  templateUrl: './classbindingexample.component.html',
  styleUrls: ['./classbindingexample.component.css']
})
export class ClassbindingexampleComponent {
  flag:boolean=false;
}


Output





ngClass with Array:


This is very much similar to the previous example i.e. applying multiple css classes. The difference is only the way you applying the css classes. The syntax to use ngClass with Array is given below. Here, you need to use one square bracket and then you need to specify the classes in a single quotes separated by a comma.

.Html changes

<h3 [ngClass]="['three', 'four', 'five']">
    Angular ngClass with String
</h3>























Output
















Same can be done with true/false as shown below

<h3 [ngClass]="{'one':true, 'two':false, 'three':true}">
    Angular ngClass with String
</h3>

Output














Second way ->

<h3 [class]="{'one':true, 'two':false, 'three':true}">
    Angular ngClass with String
</h3>

Output



















ngClass with Method

In this Class will be applied on the method return value.

Example

export class ClassbindingexampleComponent {
  flag:boolean=false;  
  AddCSSClasses(flag:string) {
      let Cssclasses;
      if(flag == "type2")
      {
        Cssclasses = {
          'one' : true,
          'two' : true
        }
      }
      else
      {
        Cssclasses = {
          'four' : true,
          'five' : true
        }
      }
      return Cssclasses;
  }
}


.html Changes

<style>
    .c1{
        background-color: black;
        color:white;
        border:5px solid yellow;
        width:30%;
        padding: 10px;
        margin: 20px;
    }
    .one{ color: red; }
    .two{ font-size: 30px; }
    .three{ font-weight: bold; }
    .four{ font-style: italic; }
    .five{ color: green; }
</style>
<h2 [class.c1]="flag">Rajakonda Uday Kumar</h2>
<br>
<input type="checkbox" [(ngModel)]="flag">Apply CSS
<h3 [ngClass]="AddCSSClasses('type1')">
    Angular ngClass with String
</h3>


Output
















Difference between

style binding-->single characteristic
          
                      textcolor,showhide  variables
                                                                 ==>complex with style binding
                        <h2 [style.color]="textcolor"                        |
                          [style.visibility]="showhide">res..</h2>   the solution is                                                                                                ngstyle


    ngstyle      -->multiple characteristics
                     
                      mystyle={"color":..,"visibility":..};    ==>simple

                      <h2 [style]="mystyle">..</h2>

    ngclass      --> styling based on css classes



Attribute Directive Part 1-->Angular ngStyle Directive Example

 ngStyle directive:

------------------
*this is used to apply stylesheet[mostly multiple characteristics] to a html element,the
 stylesheet created with in a component class (or) stylesheet based on a condition
*syntax:
   <tagname [ngStyle]="stylesheetvarname">

     or

   <tagname [ngStyle]="{characteristicname:cond?value1:value2,...}">


What is the Angular ngStyle Directive?

The ngStyle directive is used to set the DOM element style properties. For example, if you want to create a button with font size 20, the color red and font-weight bold, then you could do the same using the Angular ngStyle directive as shown in the below image.








.html changes

<button [ngStyle]="{'color':'red',  'font-weight': 'bold', 'font-size.px':20}">
Click Me </button>


Output



In the above example we have hardcoded the values, now i want to apply styles dynamically. then i need to make changes as below in ts , html files

.ts

export class AttributestylebindingComponent {
  AddButtonCSSStyles() {
    let CssStyles = {        
        'color':'blue',
        'font-weight': 'bold',
        'font-size.px': 20
    };
    return CssStyles;
  }
}


.html

<button [ngStyle]="AddButtonCSSStyles()">Click Me </button>

Output












Example 2:

When I click on sum--> I want one style to be applied
When I click on multiply-->I want one style to be applied.


.ts Changes

export class AttributestylebindingComponent {
  AddButtonCSSStyles() {
    let CssStyles = {        
        'color':'blue',
        'font-weight': 'bold',
        'font-size.px': 20
    };
    return CssStyles;
  }
  a:number=0;
  b:number=0;
  res:number=0;
  //prepare stylesheet
 mystyle={"color":"","visibility":"hidden"};
 sum()
 {
   this.res=this.a+this.b;
   this.mystyle={"color":"green","visibility":"visible"};
 }
 mult()
 {
   this.res=this.a*this.b;
   this.mystyle={"color":"red","visibility":"visible"};
 }
}


html changes

<button [ngStyle]="AddButtonCSSStyles()">Click Me </button>
<div style="font-size:x-large;margin:20px">
    enter a:<input type="number" [(ngModel)]="a"> <br>
    enter b:<input type="number" [(ngModel)]="b"> <br>
    <input type="button" value="sum" (click)="sum()">
    <input type="button" value="mult" (click)="mult()">
    <br>
    <h3 [ngStyle]="mystyle">result:{{res}}</h3>
    </div>

Output









Example

Apply styles based on gender -->Male/Female

.ts changes

export class AttributestylebindingComponent {
  students: any[] = [
    {
        Name: 'Uday', Branch: 'CSE', Gender: 'Male'
    },
    {
        Name: 'Abc', Branch: 'ETC', Gender: 'Male'
    },
    {
        Name: 'Def', Branch: 'CSE',  Gender: 'Female'
    },
    {
        Name: 'Ghi', Branch: 'ETC', Gender: 'Female'
    },
    {
        Name: 'Jkl', Branch: 'CSE', Gender: 'Male'
    }
  ];
}


.html Changes

<div *ngFor='let student of students'>
    <span [ngStyle] ="{'background-color':student.Gender === 'Male' ? 'yellow' : 'green'}">
        Name : {{student.Name}},
        Gender: {{student.Gender}},
        Branch: {{student.Branch}}
    </span>      
 </div>


Output
















Directives in Angulars

Angular is providing directives to extend the functionality | behavior of
 html.

Angular directives looks like html tag (or) attribute

 <h2>..</h2>   --> html tag


 <app-root>    -->component directive
                  [looks like html tag]
 <app-body>


 <font size="..">
          |
     html attribute

 <input .. [(ngModel)]="price">
               |
          attribute directive [looks like html attribute]

 <td *ngIF="..">
        |
   structural directive[looks like html attribute]

 In other words, we can say that the directives are basically used to extend the power of HTML attributes and to change the appearance or behavior of a DOM element.

Angular supports 3 types of directives
 1.component directive
    ->directive based on a template is called "component directive"
    ->component directive name is based on selector, component can be
      referenced from markup using selector
    ->component directive acts like a custom html tag

 2.attribute directive
    ->directive looks html element attribute is called
      "attribute directive"
    ->attribute directive will apply styling (or) extend functionality
      of html element
        eg: ngModel,ngStyle,ngClass,..

 3.structural directive
      ->directive prefixed with asterik[*] symbol is called
        "structural directive"
      ->structural directive can be used to apply control stat to
        html element
             eg: *ngIf,*ngSwitchCase,*ngFor
      ->structural directive will add|remove html element from
        browser DOM dynamically


eg:
        <table *ngIF="prods.length>0">
         <tr>                   |
       <th>pid</td>          true--table will be loaded into browser dom for display
           ..                         false--table will not be loaded into browser dom,so it will 
         </tr>                      not be shown
           ...                        |
        </table>          this provides better performance



In the next article we will deal with each example



Attribute Binding in Angular Sample Example

 Please Refer to the previous example of mine. 

https://dotnetbyudayrajakonda.blogspot.com/2023/10/angular-event-binding.html


Attribute Binding:  Binding component variable to html Element is  called as Attribute Binding.

Syntax:

<tagname [attr.attributename]="varname" >

atrribute binding is required when html element attribute is not having corresponding DOM object property.


html element                                                     DOM


<input type="text"-------------------------> text box object

 value="..."                                                value property


td colspan="..."----------------------------->td[table data] obje

                                        no colspan property , so this required attribute binding






.html changes



output










Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...