Wednesday, October 18, 2023

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










Two Way DataBinding Sample Example

Synchronizing data between component and template is called "two way databinding"

*Example:

price -100------------------->textbox-100 (input [value]="price" >---?property binding
                                                now textbox is edited
   <------------200 [ input    (input) = "price  =$event.target.value">  ]
                                                                           eventbinding

*two way databinding is a combination of property binding and event binding
*whenever textbox is edited,input event will be executed
*$event is an event handler,which will provide complete details of an event
 occured[includes controlname,..]
*$event.target will provide access to the control to which an event as
 occurred the above case it will be textbox control,textbox property value
 can be used to read textbox data



The two-way data binding is basically used in the input type filed or any form 
element where the user type or provide any value or change any control value on 
the one side and on the other side, the same automatically updated into the 
component variables and vice-versa is also true.

Example

create a component



.ts 

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

@Component({
  selector: 'app-twowaydatabinding',
  templateUrl: './twowaydatabinding.component.html',
  styleUrls: ['./twowaydatabinding.component.css']
})
export class TwowaydatabindingComponent {
  username:string="xxxxx";

  m1(event:Event)
  {
    this.username=(event.target as HTMLInputElement).value;
  }
}

.html

<div style="font-size:x-large;margin:20px">
    enter username:<input type="text" [value]="username" (input)="m1($event)">
    <br>
    Hi,{{username}}
</div>


From the above code, we need to understand two things.(Property Binding)

  1. <input [value]=’username’>: it binds the component class “username” property to the value property of the input element.
  2. Hi, {{Name}}: The Interpolation displays the value we have in the “username” property of the Component class on the web page.
So, Initially when you browse the output is



















At this moment if you change the value in the textbox, then that changed value is not going to be reflected in the browser (i.e. in the second line i.e. after you entered string). There are two different mechanisms that you can use to make them reflected (i.e. two-way data binding).


From the above code, we also need to understand about event binding

Let’s understand the above code  

  1. [value]=’username: This is property binding and it flows the data from the component class Name property to element property i.e. value property of the input element.
  2. (input)=’username= $event.target.value’: This is event binding and it flows the data in the opposite direction i.e. from the element to the component class property i.e. “username”
  3. $event: It is provided by angular event binding and it contains the event data. To retrieve the values from the input element, you need to use it as – $event.target.value.
  4. username= $event.target.value: This expression updates the value in the Name property of the component class
  5. Hi: {{username}}: This interpolation expression will then display the updated value on the web page.

*event.target will provide generic html element, it should be type casted
 to html input element[textbox],value prop can be used to read textbox data

    (event.target as Htmlinputelement).value



Angular12+ makes strict type casting by default, this requires explicit
 type casting[done above]

*developer can remove strict type casting by setting an option in
 tsconfig.json
    ->goto explorer window and select tsconfig.json
                   ...
       "compilerOptions":{
                         ...
                 "strict":false [default is true]
                         ...
                        }
        "angularCompilerOptions":{
                           ...
               "strictTemplates":false  [   "  ]
                           ..
                                }

     


Now, two way data binding can also achieve using ngModel 

*this is used to implement twoway databinding
*syntax:
  <tagname [(ngModel)]="varname">
           |        |
       property +  event
       binding     binding

*ngmodel will implement property binding and event binding automatically
*ngModel can be applied to input,textarea and select tags
*ngModel directive comes with FormsModule

 FormsModule                       AppModule
    |                                 |
 ngModel directive   ------------->imports:[FormsModule]
                                   components---> <input [(ngModel)]="varname">


Now, let us change the above code to ngModel as below

<input type="text" [value]="username" (input)="m1($event)">

to

<input [(ngModel)]='username'>


IF , we run this we will get an error, because ngModel is available in FormsModule, so we need to import that in appmodule.ts as shown below



















.html changes

<div style="font-size:x-large;margin:20px">
    enter username: <input [(ngModel)]='username'>
    <br>
    Hi,{{username}}
</div>


Output











Example

.ts changes
















.html changes




















Tuesday, October 17, 2023

Angular Event Binding Sample Example

 In the previous Example, we have seen the data flow from component to Html. In this example we will learn how the data flow from html to component.

When a user interacts with an application in the form of a keyboard movement, button click, mouse over, selecting from a drop-down list, typing in a textbox, etc. it generates an event. These events need to be handled to perform some kind of action.


Binding component class method to html element event is called "event binding"
Syntax:
   <tagname (eventname)="methodname">

Event binding requires parenthesis ()

Angular event names are similar to html event names without "on" keyword
   html events                  angular events
       |                             |
    onclick                        click
    onmouseenter                   mouseenter
    onmouseleave                   mouseleave
         ..                           ..

 <input type="button"  onclick=".."  (click)="..">

 ->html event requires javascript function
 ->angular event requires component class method

With event binding, you can also use the on- prefix alternative . This is known as the canonical form. It’s up to you which approach you follow. Behind the scene, they are going to perform the same task.

Sample Examples on Event Binding











Make the following changes in .ts file

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

@Component({
  selector: 'app-eventbinding',
  templateUrl: './eventbinding.component.html',
  styleUrls: ['./eventbinding.component.css']
})
export class EventbindingComponent {
  onClick(): void {
    console.log('Button is Clicked');
   }
   msg:string="";
  textcolor:string="blue";

  m1(s:string)
  {
    this.msg=s;
  }
  m2(){
    this.msg="";
  }
}

.html changes

<button (click)="onClick()">Click Me </button>
<button (mouseenter)="m1('user details will be saved')" (mouseleave)="m2()">Register</button>
<h3 [style.color]="textcolor">{{msg}}</h3>

Output

When we click on Click Me

























When we mouse over on the Register Button , the below message




Execution flow:
---------------
  mouseleave
  <---------register button<------mouseenter
  |                                  | user details ..
  |      {{msg}}<-------------------m1(s){
  |         |                          this.msg=s; }
  |     user details will be saved
 m2()
 {           |
  this.msg="";
 }  


Working with Tables

We will add a Show Details Buttons based on that we will display the image


.ts file change

import { Component } from '@angular/core';
import { Prods } from 'src/Prods';
@Component({
  selector: 'app-eventbinding',
  templateUrl: './eventbinding.component.html',
  styleUrls: ['./eventbinding.component.css']
})
export class EventbindingComponent {
  onClick(): void {
    console.log('Button is Clicked');
   }
   msg:string="";
  textcolor:string="blue";
  m1(s:string)
  {
    this.msg=s;
  }
  m2(){
    this.msg="";
  }
  public Product: Prods[] =[
    new Prods('Samsung', 122,'assets\\Samsung.jpg'),
    new Prods('Sony', 1252,'assets\\Sony.jpg'),
    new Prods('Iphone', 1232,'assets\\Iphone.jpg'),
    new Prods('OnePlus', 1822,'assets\\OnePlus.jpg')
  ];
   
    ShowDetails: boolean = false;
    ToggleDetails(): void {
        this.ShowDetails = !this.ShowDetails;
    }
}

.html Changes

<button (click)="onClick()">Click Me </button>
<button (mouseenter)="m1('user details will be saved')" (mouseleave)="m2()">Register</button>
<h3 [style.color]="textcolor">{{msg}}</h3>
<h1> Table with Event Binding</h1>
<table>
    <thead>
        <tr>
            <th>
                Product Details
           </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let products of Product">
            <td>{{products.Name}}</td>
            <td>{{products.Price}}</td>
            <td *ngIf='ShowDetails'> <img [src]="products.Photo" width="100" height="100" > </td>
        </tr>
    </tbody>
</table>
<br/>
<button (click)='ToggleDetails()'>
    {{ShowDetails ? 'Hide' : 'Show'}} Details
</button>




On Clicking on Show Details









Style Binding Example In Angular

  It is basically used to set the style in HTML elements. 

Syntax:
   <tagname [style.characteristic]="varname">
                       |
                    color
                    background-color

Some styles like font-size have a unit extension. To set the font-size in pixels, use below syntax

<button style='color:red' [style.font-size.px]="FontSize">Click Me
                </button>


Example:

I am going to use the previous example only.

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


.html changes















 <button style='color:red' [style.font-weight]="IsBold ? 'bold' : 'normal'">Click Me
      </button>
















Output


Multiple Inline
Styles


use NgStyle directive

Make below changes to the .ts file






















 IsBold: boolean = false;
  FontSize: number = 40;
  IsItalic: boolean = true;
  safeurl:any;
  AddingStyles() {
    let CssStyles = {
        'font-weight': this.IsBold ? 'bold' : 'normal',
        'font-style': this.IsItalic ? 'italic' : 'normal',
        'font-size.px': this.FontSize
    };

    return CssStyles;


.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...