Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE.eu :: Angular Directives 101

clock October 22, 2024 07:36 by author Peter

If you have been working with Angular directives for quite some time now, this article may help you as a refresher; if you are a beginner, this may get you started with Angular directives. We’ll try to break down the concept into its core parts and give easy examples to understand and approach.


Okay, then, let’s try to get started.

What is an Angular Directive?

Angular directives are HTML attributes that extend the behavior or the appearance of a standard HTML element. In other words, we can say that directives are simply instructions to the DOM. That’s why when we apply a directive to an HTML element or even an Angular component, we can add custom behavior or alter its appearance.
The excellent thing is that Angular provides a set of built-in directives that we can use in our components to cover most use cases.
These Angular built-in directives are part of the CommondModule.

So, we need to import CommonModule when we want to use them.

See an example of importing the built-in directives below.
import {NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';

For more information, you can check this official documentation https://v17.angular.io/api/common/CommonModule.

Types of Directives

We need to know the types of directives when dealing with Angular.

Let’s see them one by one.

Component Directives

These are directives with an associated template.
That’s why this is the commonly used directive in Angular application development.
Let’s see an example below.
import { Component } from '@angular/core';

@Component({
  selector: 'app-component-directives-sample',
  standalone: true,
  imports: [],
  templateUrl: './component-directives-sample.component.html',
  styleUrl: './component-directives-sample.component.css'
})
export class ComponentDirectivesSampleComponent {

}

From our example above, if you are already familiar with components and how to generate components.
That’s fundamentally it.
Just remember that all components are directives, but not all directives are components.
Components extend the concept of directives by providing a view (template) to render.

Structural Directives

Structural directives are used to manage the elements from the DOM, such as adding or removing elements. If a developer is building dynamic and interactive web applications with Angular, managing the display of elements based on certain conditions or iterating over a collection is essential.

Angular provides three powerful structural directives to handle these scenarios: *ngIf, *ngSwitch, and *ngFor.

Let’s dive into how these directives work and how to use them.
The *ngIf

This directive allows you to conditionally display or remove an element from the DOM based on a boolean expression.
If the condition is evaluated as true, the element is rendered; otherwise, it is removed from the DOM.
See the example below.

app.component.ts
import { Component } from '@angular/core';
import {NgIf} from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [NgIf],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'sampleDirectives';
  showProduct: boolean = true;
  products:Array<any>= [
    { id: 1,
      name: "Intel Core i9-11900K",
      type: "CPU"
    },
    {
      id: 2,
      name: "AMD Ryzen 9 5950X",
      type: "CPU"
    }
  ];
}


app.component.html
<div *ngIf="showProduct">
  <h2 [innerText]="products[0].type"></h2>
  <p [innerText]="products[0].name"></p>
</div>

From our sample code, we have the showProduct set to true and a product array to hold dummy product data.
With this view, we have decided to get the first index item of the products array.
As a result, the HTML view will show the product type and the product name.
See the output below.

The *ngSwitch
As you can see, the *ngIf works excellent for a single condition, while *ngSwitch is more efficient when you need to toggle between multiple options.
It looks almost like a switch-case statement in programming, where you can choose between different elements to render based on an expression.

See the example below.

app.component.ts
import { Component } from '@angular/core';
import {NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ NgIf, NgSwitch, NgSwitchCase, NgForOf],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'sampleDirectives';
  showProduct: boolean = true;
  products:Array<Product>= [
    { id: 1,
      name: "Intel Core i9-11900K",
      type: "CPU"
    },
    {
      id: 2,
      name: "AMD Ryzen 9 5950X",
      type: "CPU"
    },
    {
      id: 3,
      name: "EVGA SuperNOVA 850 G5",
      type: "Power Supply"
    },
    {
      id: 4,
      name: "G.Skill Ripjaws V Series 32GB",
      type: "Memory"
    }
  ];
  firstProduct: Product;
  secondProduct: Product;
  thirdProduct: Product;

  constructor() {
    this.firstProduct = this.products[0];
    this.secondProduct = this.products[1];
    this.thirdProduct = this.products[2];
  }
}

export class Product {
  id: number = 0;
  name: string = "";
  type: string = "";
}


app.component.html
<div [ngSwitch]="thirdProduct.type">
  <h2 [innerText]="thirdProduct.type"></h2>
  <p [innerText]="thirdProduct.name"></p>
  <p *ngSwitchCase="'CPU'">
    This product is a CPU.
  </p>
  <p *ngSwitchCase="'Memory'">
    This is a RAM (Random Access Memory).
  </p>
  <p *ngSwitchCase="'Power Supply'">
    This is a Power Supply.
  </p>
</div>


As a result, the HTML view will show the product type and the product name.

See the output below.

The *ngFor
I know what you are thinking if you have been dealing with programming. *ngFor is used to repeat an element for each item in a collection. Looks like a loop, right?
From our previous example, we won’t change “app.component.ts.”
We’ll add the *ngFor inside the app.component.html.
Let’s see an example below.

app.component.html
<div>
  <ul>
    <li *ngFor="let product of products">
        <h2 [innerText]="product.name"></h2>
        <p [ngSwitch]="product.type">
          <span *ngSwitchCase="'CPU'">
            This product is a CPU.
          </span>
          <span *ngSwitchCase="'Memory'">
            This is a RAM (Random Access Memory).
          </span>
          <span *ngSwitchCase="'Power Supply'">
            This is a Power Supply.
          </span>
        </p>
    </li>
  </ul>
</div>


As a result, the HTML view will show an unordered list of products.
See the output below.

Attribute Directives
Attribute directives modify the appearance of or define a custom behavior for a DOM element.
Angular has a rich set of built-in directives that allow dynamic styling and classes to be applied.
Among these directives, ngClass and ngStyle are essential tools for any Angular developer.

Let’s try to explore them one by one.

The ngClass
We can use this directive ngClass to add or remove CSS classes dynamically.
Moreover, developers can use this directive to apply one or more CSS classes to an element conditionally.
You can pass a string, array, or object to ngClass to control which classes should be added or removed.
You can use either the expression or method with the ngClass directive.

Using Expression
A developer can’t write if condition within the ngClass directive.

However, we can use the ternary operator as this is an expression.
//Syntax
[ngClass]="condition ? 'when true apply class' : 'when false apply class'"
//Syntax (multiple classes)
[ngClass]="condition ? 'when true apply class1 class2' : 'when false apply class1 class2'"


Let’s have an example below.
attribute-directive-samp.component.css

.dot {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  display: inline-block;
  background-color: #c1bbbb;
}
.dot-border-red {
  border-color: red;
  border-style: dotted;
  border-width: 3px;
}

.dot-border-yellow {
  border-color: yellow;
  border-style: dotted;
  border-width: 3px;
}
.yellow {
  background-color: yellow;
}

.red {
  background


attribute-directive-samp.component.ts
import { Component } from '@angular/core';
import {NgClass} from '@angular/common';

@Component({
  selector: 'app-attribute-directive-samp',
  standalone: true,
  imports: [
    NgClass
  ],
  templateUrl: './attribute-directive-samp.component.html',
  styleUrl: './attribute-directive-samp.component.css'
})
export class AttributeDirectiveSampComponent {
  isYellow = false;
  isRed: boolean = false;

  colorChanged(value:string): void {
    if(value === 'R'){
      this.isRed = true;
      this.isYellow = false;
    }
    else if(value === 'Y'){
      this.isYellow = true;
      this.isRed = false;
    }
  }
}

attribute-directive-samp.component.html
<h3>Using Expression</h3>
<input type="radio" name="firstDot" value="R" (change)="colorChanged('R')" /> Red
<input type="radio" name="firstDot" value="Y" (change)="colorChanged('Y')" /> Yellow
<br/>
<div class="dot" [ngClass]="isRed ? 'dot red dot-border-yellow': 'dot yellow dot-border-red'">
</div>

From our example, we have seen that we can change the circle’s background color and border when choosing between red and yellow.
We have achieved this by using an expression inside the ngClass.

Output


Using Function
Developers can apply CSS classes through various methods in complex conditions.

For example, you can use this way to set a CSS class based on user input.

Let’s see an example below.
attribute-directive-samp-using-function.component.css

.dot {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  display: inline-block;
  background-color: #c1bbbb;
}
.dot-border-red {
  border-color: red;
  border-style: dotted;
  border-width: 3px;
}

.dot-border-yellow {
  border-color: yellow;
  border-style: dotted;
  border-width: 3px;
}
.yellow {
  background-color: yellow;
}

.red {
  background-color: red;
}

attribute-directive-samp-using-function.component.ts
import { Component } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {NgClass} from '@angular/common';

@Component({
  selector: 'app-attribute-directive-samp-using-function',
  standalone: true,
  imports: [
    FormsModule,
    NgClass
  ],
  templateUrl: './attribute-directive-samp-using-function.component.html',
  styleUrl: './attribute-directive-samp-using-function.component.css'
})
export class AttributeDirectiveSampUsingFunctionComponent {
  selectedColor: string = "";

  getClassColorValue(): string {
    let classToReturn = '';
    if(this.selectedColor === 'Red'){
      classToReturn = 'dot red dot-border-yellow';
    }
    else if(this.selectedColor === 'Yellow'){
      classToReturn = 'dot yellow dot-border-red';
    }
    return classToReturn;
  }
}


attribute-directive-samp-using-function.component.html
<h3>Using Function</h3>
<input type="radio" name="secondDot" value="Red" [(ngModel)]="selectedColor" /> Red
<input type="radio" name="secondDot" value="Yellow" [(ngModel)]="selectedColor" /> Yellow
<br/>
<div class="dot" [ngClass]="getClassColorValue()"></div>


From our example, we have seen that we can change the circle’s background color and border when choosing between red and yellow.
However, instead of an expression, we used a method or function where the class was set inside the ngClass.
Note. For both examples, we use the same styles for attribute-directive-samp.component.css and attribute-directive-samp-using-function.component.css.
Again, we have achieved our goal for both examples, but by using different approaches, it's up to the developer to choose either expression or method/function.

Output

 

The ngStyle
Developers, when using the ngStyle directive, allow them to set the style property of the DOM element.

People suggest directly putting styles inside the style attribute isn’t that good.
But in our case, and for educational purposes, we need to understand that this directive is available for us to use in some cases.

Let’s see an example.

attribute-directives-ngstyle.component.ts

import {Component} from '@angular/core';
import {NgStyle} from '@angular/common';
import {FormsModule} from '@angular/forms';

@Component({
  selector: 'app-attribute-directives-ngstyle',
  standalone: true,
  imports: [
    NgStyle,
    FormsModule
  ],
  templateUrl: './attribute-directives-ngstyle.component.html',
  styleUrl: './attribute-directives-ngstyle.component.css'
})
export class AttributeDirectivesNgstyleComponent {

  isBold : boolean = false;
  isItalic:boolean = false;
  isUpperCase: boolean = false;


  setElementStyle() {
    return {
      'font-weight': this.isBold ? 'bold' : 'normal',
      'font-style': this.isItalic ? 'italic' : 'normal',
      'text-transform': this.isUpperCase ? 'uppercase' : 'none'
    };
  }
}

attribute-directives-ngstyle.component.html

<p>
  Let us style the text below.
  <br/>
  Bold: <input type="checkbox" [(ngModel)]="isBold"  /> <br/>
  Italic: <input type="checkbox" [(ngModel)]="isItalic" /> <br/>
  UpperCase: <input type="checkbox" [(ngModel)]="isUpperCase" /> <br/>
</p>
<div [ngStyle]="setElementStyle()">I love Angular</div>


From our example, we have built an object that checks whether the checkboxes are checked, which makes the isItalic, isUpperCase, and isBold true or false with specific values at runtime.

Then, it will be returned as an object assigned to the ngStyle directive.

See the output below.


Summary
In this post, we have discussed the three types of directives: component, structural, and attribute. However, component directives seem straightforward to most of us developers. We have seen a lot of examples of structural and attribute directives, and the examples we have are the built-in directives for these types of directives built into the Angular library for most use cases. I hope you have enjoyed this article as much as I have enjoyed writing it.
Stay tuned for more information, and don't forget to download the attached project source code.
If you run the project source code, don’t forget to command “npm install.”
Until next time, happy programming, and good luck with your career!



AngularJS Hosting Europe - HostForLIFE.eu :: Angular Directives 101

clock October 22, 2024 07:36 by author Peter

If you have been working with Angular directives for quite some time now, this article may help you as a refresher; if you are a beginner, this may get you started with Angular directives. We’ll try to break down the concept into its core parts and give easy examples to understand and approach.

Okay, then, let’s try to get started.

What is an Angular Directive?

Angular directives are HTML attributes that extend the behavior or the appearance of a standard HTML element. In other words, we can say that directives are simply instructions to the DOM. That’s why when we apply a directive to an HTML element or even an Angular component, we can add custom behavior or alter its appearance.
The excellent thing is that Angular provides a set of built-in directives that we can use in our components to cover most use cases.
These Angular built-in directives are part of the CommondModule.

So, we need to import CommonModule when we want to use them.

See an example of importing the built-in directives below.
import {NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';

For more information, you can check this official documentation https://v17.angular.io/api/common/CommonModule.

Types of Directives

We need to know the types of directives when dealing with Angular.

Let’s see them one by one.

Component Directives

These are directives with an associated template.
That’s why this is the commonly used directive in Angular application development.
Let’s see an example below.
import { Component } from '@angular/core';

@Component({
  selector: 'app-component-directives-sample',
  standalone: true,
  imports: [],
  templateUrl: './component-directives-sample.component.html',
  styleUrl: './component-directives-sample.component.css'
})
export class ComponentDirectivesSampleComponent {

}

From our example above, if you are already familiar with components and how to generate components.
That’s fundamentally it.
Just remember that all components are directives, but not all directives are components.
Components extend the concept of directives by providing a view (template) to render.

Structural Directives

Structural directives are used to manage the elements from the DOM, such as adding or removing elements. If a developer is building dynamic and interactive web applications with Angular, managing the display of elements based on certain conditions or iterating over a collection is essential.

Angular provides three powerful structural directives to handle these scenarios: *ngIf, *ngSwitch, and *ngFor.

Let’s dive into how these directives work and how to use them.
The *ngIf

This directive allows you to conditionally display or remove an element from the DOM based on a boolean expression.
If the condition is evaluated as true, the element is rendered; otherwise, it is removed from the DOM.
See the example below.

app.component.ts
import { Component } from '@angular/core';
import {NgIf} from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [NgIf],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'sampleDirectives';
  showProduct: boolean = true;
  products:Array<any>= [
    { id: 1,
      name: "Intel Core i9-11900K",
      type: "CPU"
    },
    {
      id: 2,
      name: "AMD Ryzen 9 5950X",
      type: "CPU"
    }
  ];
}


app.component.html
<div *ngIf="showProduct">
  <h2 [innerText]="products[0].type"></h2>
  <p [innerText]="products[0].name"></p>
</div>

From our sample code, we have the showProduct set to true and a product array to hold dummy product data.
With this view, we have decided to get the first index item of the products array.
As a result, the HTML view will show the product type and the product name.
See the output below.

The *ngSwitch
As you can see, the *ngIf works excellent for a single condition, while *ngSwitch is more efficient when you need to toggle between multiple options.
It looks almost like a switch-case statement in programming, where you can choose between different elements to render based on an expression.

See the example below.

app.component.ts
import { Component } from '@angular/core';
import {NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ NgIf, NgSwitch, NgSwitchCase, NgForOf],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'sampleDirectives';
  showProduct: boolean = true;
  products:Array<Product>= [
    { id: 1,
      name: "Intel Core i9-11900K",
      type: "CPU"
    },
    {
      id: 2,
      name: "AMD Ryzen 9 5950X",
      type: "CPU"
    },
    {
      id: 3,
      name: "EVGA SuperNOVA 850 G5",
      type: "Power Supply"
    },
    {
      id: 4,
      name: "G.Skill Ripjaws V Series 32GB",
      type: "Memory"
    }
  ];
  firstProduct: Product;
  secondProduct: Product;
  thirdProduct: Product;

  constructor() {
    this.firstProduct = this.products[0];
    this.secondProduct = this.products[1];
    this.thirdProduct = this.products[2];
  }
}

export class Product {
  id: number = 0;
  name: string = "";
  type: string = "";
}


app.component.html
<div [ngSwitch]="thirdProduct.type">
  <h2 [innerText]="thirdProduct.type"></h2>
  <p [innerText]="thirdProduct.name"></p>
  <p *ngSwitchCase="'CPU'">
    This product is a CPU.
  </p>
  <p *ngSwitchCase="'Memory'">
    This is a RAM (Random Access Memory).
  </p>
  <p *ngSwitchCase="'Power Supply'">
    This is a Power Supply.
  </p>
</div>


As a result, the HTML view will show the product type and the product name.

See the output below.

The *ngFor
I know what you are thinking if you have been dealing with programming. *ngFor is used to repeat an element for each item in a collection. Looks like a loop, right?
From our previous example, we won’t change “app.component.ts.”
We’ll add the *ngFor inside the app.component.html.
Let’s see an example below.

app.component.html
<div>
  <ul>
    <li *ngFor="let product of products">
        <h2 [innerText]="product.name"></h2>
        <p [ngSwitch]="product.type">
          <span *ngSwitchCase="'CPU'">
            This product is a CPU.
          </span>
          <span *ngSwitchCase="'Memory'">
            This is a RAM (Random Access Memory).
          </span>
          <span *ngSwitchCase="'Power Supply'">
            This is a Power Supply.
          </span>
        </p>
    </li>
  </ul>
</div>


As a result, the HTML view will show an unordered list of products.
See the output below.

Attribute Directives
Attribute directives modify the appearance of or define a custom behavior for a DOM element.
Angular has a rich set of built-in directives that allow dynamic styling and classes to be applied.
Among these directives, ngClass and ngStyle are essential tools for any Angular developer.

Let’s try to explore them one by one.

The ngClass
We can use this directive ngClass to add or remove CSS classes dynamically.
Moreover, developers can use this directive to apply one or more CSS classes to an element conditionally.
You can pass a string, array, or object to ngClass to control which classes should be added or removed.
You can use either the expression or method with the ngClass directive.

Using Expression
A developer can’t write if condition within the ngClass directive.

However, we can use the ternary operator as this is an expression.
//Syntax
[ngClass]="condition ? 'when true apply class' : 'when false apply class'"
//Syntax (multiple classes)
[ngClass]="condition ? 'when true apply class1 class2' : 'when false apply class1 class2'"


Let’s have an example below.
attribute-directive-samp.component.css

.dot {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  display: inline-block;
  background-color: #c1bbbb;
}
.dot-border-red {
  border-color: red;
  border-style: dotted;
  border-width: 3px;
}

.dot-border-yellow {
  border-color: yellow;
  border-style: dotted;
  border-width: 3px;
}
.yellow {
  background-color: yellow;
}

.red {
  background


attribute-directive-samp.component.ts
import { Component } from '@angular/core';
import {NgClass} from '@angular/common';

@Component({
  selector: 'app-attribute-directive-samp',
  standalone: true,
  imports: [
    NgClass
  ],
  templateUrl: './attribute-directive-samp.component.html',
  styleUrl: './attribute-directive-samp.component.css'
})
export class AttributeDirectiveSampComponent {
  isYellow = false;
  isRed: boolean = false;

  colorChanged(value:string): void {
    if(value === 'R'){
      this.isRed = true;
      this.isYellow = false;
    }
    else if(value === 'Y'){
      this.isYellow = true;
      this.isRed = false;
    }
  }
}

attribute-directive-samp.component.html
<h3>Using Expression</h3>
<input type="radio" name="firstDot" value="R" (change)="colorChanged('R')" /> Red
<input type="radio" name="firstDot" value="Y" (change)="colorChanged('Y')" /> Yellow
<br/>
<div class="dot" [ngClass]="isRed ? 'dot red dot-border-yellow': 'dot yellow dot-border-red'">
</div>

From our example, we have seen that we can change the circle’s background color and border when choosing between red and yellow.
We have achieved this by using an expression inside the ngClass.

Output


Using Function
Developers can apply CSS classes through various methods in complex conditions.

For example, you can use this way to set a CSS class based on user input.

Let’s see an example below.
attribute-directive-samp-using-function.component.css

.dot {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  display: inline-block;
  background-color: #c1bbbb;
}
.dot-border-red {
  border-color: red;
  border-style: dotted;
  border-width: 3px;
}

.dot-border-yellow {
  border-color: yellow;
  border-style: dotted;
  border-width: 3px;
}
.yellow {
  background-color: yellow;
}

.red {
  background-color: red;
}

attribute-directive-samp-using-function.component.ts
import { Component } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {NgClass} from '@angular/common';

@Component({
  selector: 'app-attribute-directive-samp-using-function',
  standalone: true,
  imports: [
    FormsModule,
    NgClass
  ],
  templateUrl: './attribute-directive-samp-using-function.component.html',
  styleUrl: './attribute-directive-samp-using-function.component.css'
})
export class AttributeDirectiveSampUsingFunctionComponent {
  selectedColor: string = "";

  getClassColorValue(): string {
    let classToReturn = '';
    if(this.selectedColor === 'Red'){
      classToReturn = 'dot red dot-border-yellow';
    }
    else if(this.selectedColor === 'Yellow'){
      classToReturn = 'dot yellow dot-border-red';
    }
    return classToReturn;
  }
}


attribute-directive-samp-using-function.component.html
<h3>Using Function</h3>
<input type="radio" name="secondDot" value="Red" [(ngModel)]="selectedColor" /> Red
<input type="radio" name="secondDot" value="Yellow" [(ngModel)]="selectedColor" /> Yellow
<br/>
<div class="dot" [ngClass]="getClassColorValue()"></div>


From our example, we have seen that we can change the circle’s background color and border when choosing between red and yellow.
However, instead of an expression, we used a method or function where the class was set inside the ngClass.
Note. For both examples, we use the same styles for attribute-directive-samp.component.css and attribute-directive-samp-using-function.component.css.
Again, we have achieved our goal for both examples, but by using different approaches, it's up to the developer to choose either expression or method/function.

Output

 

The ngStyle
Developers, when using the ngStyle directive, allow them to set the style property of the DOM element.

People suggest directly putting styles inside the style attribute isn’t that good.
But in our case, and for educational purposes, we need to understand that this directive is available for us to use in some cases.

Let’s see an example.

attribute-directives-ngstyle.component.ts

import {Component} from '@angular/core';
import {NgStyle} from '@angular/common';
import {FormsModule} from '@angular/forms';

@Component({
  selector: 'app-attribute-directives-ngstyle',
  standalone: true,
  imports: [
    NgStyle,
    FormsModule
  ],
  templateUrl: './attribute-directives-ngstyle.component.html',
  styleUrl: './attribute-directives-ngstyle.component.css'
})
export class AttributeDirectivesNgstyleComponent {

  isBold : boolean = false;
  isItalic:boolean = false;
  isUpperCase: boolean = false;


  setElementStyle() {
    return {
      'font-weight': this.isBold ? 'bold' : 'normal',
      'font-style': this.isItalic ? 'italic' : 'normal',
      'text-transform': this.isUpperCase ? 'uppercase' : 'none'
    };
  }
}

attribute-directives-ngstyle.component.html

<p>
  Let us style the text below.
  <br/>
  Bold: <input type="checkbox" [(ngModel)]="isBold"  /> <br/>
  Italic: <input type="checkbox" [(ngModel)]="isItalic" /> <br/>
  UpperCase: <input type="checkbox" [(ngModel)]="isUpperCase" /> <br/>
</p>
<div [ngStyle]="setElementStyle()">I love Angular</div>


From our example, we have built an object that checks whether the checkboxes are checked, which makes the isItalic, isUpperCase, and isBold true or false with specific values at runtime.

Then, it will be returned as an object assigned to the ngStyle directive.

See the output below.


Summary
In this post, we have discussed the three types of directives: component, structural, and attribute. However, component directives seem straightforward to most of us developers. We have seen a lot of examples of structural and attribute directives, and the examples we have are the built-in directives for these types of directives built into the Angular library for most use cases. I hope you have enjoyed this article as much as I have enjoyed writing it.
Stay tuned for more information, and don't forget to download the attached project source code.
If you run the project source code, don’t forget to command “npm install.”
Until next time, happy programming, and good luck with your career!



AngularJS Hosting Europe - HostForLIFE.eu :: Integration of Angular with Microservices

clock October 10, 2024 07:00 by author Peter

I'm a slack backend.net developer. I have some knowledge of.net technologies, however I'm not very knowledgeable with Angular, a frontend JavaScript framework. In order to enable external communication between the front-end and RESTful web API services, my manager instructed me to jot down certain typescript codes. You all know what would happen if I told him I didn't know how to do it. Anyhow, let's return to the primary topic. Please be aware that this is only intended for novice users who want to fire once and forget. Please don't hold me responsible. My knowledge of typescripts is rather limited.

Resolution and Schematic Design

  • I divided the entire assignment into four sections at first:
  • Examining the options in the app.
  • Setting up an environment depends on whether it's for production, QA, or development.
  • Establishing a connection with external RESTful web API services.
  • Requests to the services that include instructions or questions.

Basic knowledge - I guess you know it. So, in short.

  • Restful web API: it’s an interface for communication with two or more applications.
  • TypeScript: Compared to javaScript, It supports writing code with object-oriented concepts.
  • Singleton design pattern: It creates a single shared instance of the object.
  • Dependency injection design pattern: It is a style of object configuration in which objects are set by an external entity.

Explanation of each of the steps

  • Step 1: Read all the configuration at runtime from the appSettings.json file so that applications can use this data at runtime.
  • Step 2: Check the environment. Is it development, QA, or production? Set the environment settings data that you got from step 1.
  • Step 3: Create a base class for the service to get the API service, for instance. Design it using the concept of the singleton design pattern. Get the settings data from step 2.
  • Step 4: The main service class calls all the get/post/put/patch/delete required requests to the RESTful web API. Add the base class from step 3.
  • Step 5: Use the dependency Injection pattern to inject the dependent service. Inject the dependent service class into the component class. Call the required methods of the service from the component class. Use the class from step 4.

Implementation of each of the classes using typeScript in the Angular project

  • appsettings-json-reader package: Read all the data from the JSON file.
  • npm install appsettings-json-reader

Axios package: Promise-based API method called.
npm install axios --save

I guess you already know how to implement step1 & step2.

Implementing steps 3
Creating the base class using a command.
ng g class BaseApiClientService

import { Injectable } from "@angular/core";
import axios from "axios";
import { AppSettingsConfig } from "../../configuration/app-settings-config";

@Injectable()
export class BaseApiClientService {
  private appSettings!: AppSettingsConfig;
  private helloApiBaseUrl!: string;

  constructor() {
    // Holding configuration-data object.
    this.appSettings = new AppSettingsConfig();

    // Getting base URL of the Hello-API.
    this.helloApiBaseUrl = this.appSettings.apiEndPoint;
  }

  // Main API Instance.
  readonly HelloApiInstance = () => {
    return axios.create({
      baseURL: this.helloApiBaseUrl,
      timeout: 5000,
      headers: {
        Accept: 'application/json',
        cors: true,
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, PATCH, OPTIONS',
      }
    });
  }
}


Implementing steps 4
Creating the service class using a command.
ng g service Hello-Api-Service

import { Injectable } from '@angular/core';
import { AxiosInstance } from 'axios';
import { ConstApiSubPathConfig } from '../../configuration/const-api-sub-path-config';
import { BaseApiClientService } from './base-api-client-service';

@Injectable({
  providedIn: 'root'
})
export class HelloAPIServiceService {
  readonly helloWebApiInstance: AxiosInstance;

  constructor(private baseClient: BaseApiClientService)
  {
    this.helloWebApiInstance = this.baseClient.HelloApiInstance();
  }

  GetHelloDataList(isActive:boolean) {
    //// It will add the pathSufix with the main base URL path.
    let pathSufix = '/' + ConstApiSubPathConfig.HelloApiSubDaListPathSufix;

    //// Get request:Returns the response.
    return this.helloWebApiInstance.get(pathSufix, {
      params: { IsActive: isActive }});
  }

  AddHelloMessage(helloMessageObj: any) {
    let pathSufix = '/' + ConstApiSubPathConfig.HelloApiSubPathSufix;

    //// Post request:Returns the response.
    return this.helloWebApiInstance.post(pathSufix, helloMessageObj);
  }
}

Implementing Steps 5
Creating the component class using a command.
ng g component HelloServiceGrid --module app

import { Component } from '@angular/core';
import { HelloAPIServiceService } from '../../../core/service/axios-service/hello-api-service.service';

@Component({
  selector: 'app-hello-service-grid',
  templateUrl: './hello-service-grid.component.html',
  styleUrls: ['./hello-service-grid.component.css']
})
export class HelloServiceGridComponent {
  constructor( private api: HelloAPIServiceService){  }
  getHelloDataList()
  {
      let isActive:boolean = true;
      this.api.GetHelloDataList(isActive)
      .then(response => {

        //// if status-code is success.
        if (response.status === 200) {
          /// Response Data from API.
          let result = response.data;

          //// Implement your logic with the data below:
        }
      }).catch(error => console.log('Error message =====> Sorry : ' + error.message));
  }
}


Don’t forget to check the App.module.ts file. Your components should be added to the declarations array, and your services should be added to the providers array.


I'll go over how to define environmental configurations and read configurations at runtime in the next section, which covers leveraging Azure DevOps CI/CD pipelines to deploy an Angular app to the Azure environment. Anyhow, I have to leave.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Apply CRUD Operations in Dynamic Grid Using AngularJS?

clock October 3, 2024 08:08 by author Peter

I explained How to Show Data in a Dynamic Grid Using AngularJS in my earlier article. I'll explain in this article how to use AngularJS to apply CRUD operations in a dynamic grid. I previously shown to you how to display data in a grid format, but in this post, we'll take it a step further and enable editing of the grid; in other words, I'll be providing CRUD functions for the grid.

Step 1: Since I'm working on an earlier application, you may see where I left off in that post by reading it.
Now, I will update the JavaScript section and will provide the edit and delete functionality. For that, you need to write this code in the script section.
$scope.delete = function(id) {
    for (i in $scope.employees) {
        if ($scope.employees[i].id == id) {
            $scope.employees.splice(i, 1);
            $scope.newEmployee = {};
        }
    }
}

$scope.edit = function(id) {
    for (i in $scope.employees) {
        if ($scope.employees[i].id == id) {
            $scope.newEmployee = angular.copy($scope.employees[i]);
        }
    }
}


First, I provided the delete functionality; for this, I have created a function named "delete". In this function the ID of the Employee is passed, if the ID correctly matches one of the existing IDs then the delete operation will be done and that entry will be deleted.

Similarly, I have created the "Edit" function. In this function, the ID of the Employee will also be passed, but this time the data related to that ID will not be deleted. Instead, it will be passed back to the corresponding textboxes so that the user can make changes, and when the user clicks the save button, the data will again be saved at the same Id position as it was stored previously.

Now, the updated Script looks like this.
<script>
    var empid = 1;

    function x($scope) {
        $scope.employees = [
            { id: 0, 'name': 'Anubhav', 'address': 'Ghaziabad', 'dept': 'Developer' }
        ];

        $scope.saveRecord = function() {
            if ($scope.newEmployee.id == null) {
                $scope.newEmployee.id = empid++;
                $scope.employees.push($scope.newEmployee);
            } else {
                for (i in $scope.employees) {
                    if ($scope.employees[i].id == $scope.newEmployee.id) {
                        $scope.employees[i] = $scope.newEmployee;
                    }
                }
            }
            $scope.newEmployee = {};
        }

        $scope.delete = function(id) {
            for (i in $scope.employees) {
                if ($scope.employees[i].id == id) {
                    $scope.employees.splice(i, 1);
                    $scope.newEmployee = {};
                }
            }
        }

        $scope.edit = function(id) {
            for (i in $scope.employees) {
                if ($scope.employees[i].id == id) {
                    $scope.newEmployee = angular.copy($scope.employees[i]);
                }
            }
        }
    }
</script>

Step 2. Now, I will work on the ViewModel of this application and will modify it as well.
You need to update your Table with this code.
<table border="1" bordercolor="blue">
    <tr style="color:blue">
        <th style="width:150px">Name</th>
        <th style="width:150px">Address</th>
        <th style="width:150px">Dept</th>
        <th>Action</th>
    </tr>
    <tr style="color:pink" ng-repeat="employee in employees">
        <td>{{ employee.name }}</td>
        <td>{{ employee.address }}</td>
        <td>{{ employee.dept }}</td>
        <td>
            <a href="#" ng-click="edit(employee.id)">edit</a> |
            <a href="#" ng-click="delete(employee.id)">delete</a>
        </td>
    </tr>
</table>


Here, in the first Row, I added one more heading, "Action". In the second row, I added one more column in which two Anchors are used.

The first Anchor click is bound to the "Edit" function, and the second Anchor click is bound to the "Delete" function.

The ID of the Employee is passed depending on the Anchors, in other words wherever the Anchors are placed, the corresponding ID will be passed to the function.

Now our View Model is updated and its code is like this.
<div ng-app="" ng-controller="x">
    <label>Name</label>
    <input type="text" name="name" ng-model="newEmployee.name"/>

    <label>Address</label>
    <input type="text" name="address" ng-model="newEmployee.address"/>

    <label>Dept.</label>
    <input type="text" name="dept" ng-model="newEmployee.dept"/>
    <br/>

    <input type="hidden" ng-model="newEmployee.id"/>
    <input type="button" value="Save" ng-click="saveRecord()" class="btn btn-primary"/>
    <br/>
    <br/>

    <table border="1" bordercolor="blue">
        <tr style="color:blue">
            <th style="width:150px">Name</th>
            <th style="width:150px">Address</th>
            <th style="width:150px">Dept</th>
            <th>Action</th>
        </tr>
        <tr style="color:pink" ng-repeat="employee in employees">
            <td>{{ employee.name }}</td>
            <td>{{ employee.address }}</td>
            <td>{{ employee.dept }}</td>
            <td>
                <a href="#" ng-click="edit(employee.id)">edit</a> |
                <a href="#" ng-click="delete(employee.id)">delete</a>
            </td>
        </tr>
    </table>
</div>


Now, our application is created and is ready for execution.



AngularJS Hosting Europe - HostForLIFE.eu :: Types of Components Selectors in Angular with Examples

clock September 12, 2024 10:29 by author Peter

Selector of Type
The HTML tag name is the basis for selects. App-root as an example. Since this kind of selection is the standard for all Angular components, you probably already know it.

Attribute Selector

  • The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-attribute-selector].
  • To use the directive, you add the app-attribute-selector attribute to any HTML element in your template.
  • The content within that element will be replaced by the template defined in the directive.

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

    @Component({
      selector: '[app-attribute-selector]',
      standalone: true,
      imports: [],
      templateUrl: './attribute-selector.component.html',
      styleUrl: './attribute-selector.component.scss'
    })
    export class AttributeSelectorComponent {

    }

component view code
<p>attribute-selector works!</p>

Attribute selector with value

  • The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-attribute-selector-with-value=” test”].
  • To use the directive, you add the app-attribute-selector-with-value=” test” attribute to any HTML element in your template.
  • The content within that element will be replaced by the template defined in the directive.


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

    @Component({
      selector: '[app-attribute-selector-with-value="test"]',
      standalone: true,
      imports: [],
      templateUrl: './attribute-selector-with-value.component.html',
      styles: ``
    })
    export class AttributeSelectorWithValueComponent {

    }


component view code
<p>attribute-selector-with-value works!</p>

The selector with multiple attributes

The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-multiple-attribute-selector="test"][is-active].
To use the directive, you add the app-multiple-attribute-selector="test" is-active attribute to any HTML element in your template.
The content within that element will be replaced by the template defined in the directive.
    import { Component } from '@angular/core';

    @Component({
      selector: '[app-multiple-attribute-selector="test"][is-active]',
      standalone: true,
      imports: [],
      templateUrl: './multiple-attribute-selector.component.html',
      styleUrl: './multiple-attribute-selector.component.scss'
    })
    export class MultipleAttributeSelectorComponent {

    }


component view code
<p>multiple-attribute-selector works!</p>

Key Points
Attribute selectors are useful when you want to apply a component to multiple elements based on a common attribute.
They are often used for directives that provide additional functionality to existing elements.
Attribute selectors are case-sensitive.

Note. For attribute values, Angular supports matching an exact attribute value with the equals (=) operator. Angular does not support other attribute value operators.
CSS Class Selector
 
Class selector
A CSS class selector is used to target elements that have a specific class attribute. The class attribute is defined within the opening tag of an HTML element and is preceded by a dot (.).
import { Component } from '@angular/core';

@Component({
  selector: '.app-css-class-selector',
  standalone: true,
  imports: [],
  templateUrl: './css-class-selector.component.html',
  styles: ``
})
export class CssClassSelectorComponent {

}


component view code
<p>css-class-selector works!</p>

:not pseudo-class

The: not pseudo-class in CSS allows you to target elements that do not match a specific selector. You can leverage this in Angular component selectors to create more targeted components.

Explanation

  • The :not(.disabled) part of the selector ensures that the component only matches elements with the class "container" that do not also have the class "disabled".
  • This provides a way to conditionally apply the component based on the presence or absence of other classes.

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

    @Component({
      selector: '.app-css-not-pseudo-selector:not(.disabled)',
      standalone: true,
      imports: [],
      templateUrl: './css-not-pseudo-selector.component.html',
      styles: ``
    })
    export class CssNotPseudoSelectorComponent {

    }


component view code

<p>css-not-pseudo-selector works!</p>

Targeting elements that are not direct children of a specific element.
@Component({
  selector: 'div:not(.parent) > p'
})
export class MyComponent {
}


Targeting elements that do not have a specific attribute.
@Component({
  selector: 'button:not([disabled])'
})
export class MyButtonComponent {
}


Key Points

  • The :not pseudo-class can be combined with other selectors to create more complex targeting rules.
  • It's a powerful tool for creating reusable components that can be applied conditionally based on the structure of your HTML.
  • Be cautious when using :not with complex selectors, as it can sometimes lead to unexpected behavior if not used correctly.

By understanding and utilizing the : not pseudo-class, you can create more flexible and targeted components in your Angular applications.

Combining selectors

You can combine selectors in Angular using CSS-like syntax to create more specific targeting rules. Here are some examples.
You can combine with Element, class, id, pseudo-class, attributes, comma-separated selectors, and so on.

Combining by Element, Class, and ID
@Component({
  selector: 'div.container#my-container'
})
export class MyComponent {
}


This component will only match elements that are.

  • A div element
  • Have the class container
  • Have the ID my-container

Combining with Pseudo-Classes
TypeScript
@Component({
  selector: 'button:not(.disabled):hover'
})
export class MyButtonComponent {
}


This component will match buttons that.

  • Do not have the class disabled
  • Are being hovered over

Combining with Attributes
TypeScript
@Component({
  selector: '[data-type="product"][is-active]'
})
export class ActiveProductComponent {
}


This component will match elements that.

  • Have the attribute data type with the value "product"
  • Have the attribute is-active

Combining Multiple Selectors

You can combine multiple selectors using commas.
TypeScript
@Component({
  selector: '.container, .card'
})
export class MyComponent {
}


This component will match elements that have either the class container or the class card.

Remember

  • Specificity: The more specific your selector is, the higher its priority.
  • Cascading Stylesheets (CSS): If multiple selectors match an element, the most specific selector takes precedence.
  • HTML Structure: Ensure that your selectors match the structure of your HTML elements.

By effectively combining selectors, you can create targeted components that accurately match the elements you intend to interact with in your Angular application.

Below is the output of the Selectors explained above.
    App.component.ts

    import { Component } from '@angular/core';
    import { RouterOutlet } from '@angular/router';
    import { AttributeSelectorComponent } from './attribute-selector/attribute-selector.component';
    import { MultipleAttributeSelectorComponent } from './multiple-attribute-selector/multiple-attribute-selector.component';
    import { AttributeSelectorWithValueComponent } from './attribute-selector-with-value/attribute-selector-with-value.component';
    import { CssClassSelectorComponent } from './css-class-selector/css-class-selector.component';
    import { CssNotPseudoSelectorComponent } from './css-not-pseudo-selector/css-not-pseudo-selector.component';
    import { CombiningSelectorsComponent } from './combining-selectors/combining-selectors.component';

    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [
        RouterOutlet,
        AttributeSelectorComponent,
        MultipleAttributeSelectorComponent,
        AttributeSelectorWithValueComponent,
        CssClassSelectorComponent,
        CssNotPseudoSelectorComponent,
        CombiningSelectorsComponent
      ],
      templateUrl: './app.component.html',
      styleUrl: './app.component.scss',
    })
    export class AppComponent {
      show = false;
      testId = 'main-cta';
      title = 'angular-dev-test';
    }

component view code
@if(show){
<button [attr.data-test-id]="testId">Show CTA</button>
} @else {
<button [attr.data-test-id]="testId">Normal CTA</button>
}

<div app-attribute-selector is-active>will be ignored</div>
<div app-attribute-selector-with-value="test">will be ignored</div>
<div app-multiple-attribute-selector="test" is-active>will be ignored</div>
<div class="app-css-class-selector">will be ignored</div>
<div class="app-css-not-pseudo-selector">will be ignored</div>
<button type="reset">Reset</button>


Page Output




AngularJS Hosting Europe - HostForLIFE.eu :: Angular Route Guard Performance and Security Optimization

clock September 6, 2024 08:53 by author Peter

The route guards provided by Angular are effective tools for controlling access control inside your application. They improve security and user experience by assisting in making sure that users can only access routes that they are permitted to view. Poorly designed route guards, however, might cause security flaws and performance snags as your program expands. In order to successfully balance performance and security, we'll look at advanced ways for improving Angular route guards in this post.

1. Understanding Angular Route Guards
Angular offers several types of route guards, each serving a specific purpose.

  • CanActivate: Determines if a route can be activated.
  • CanDeactivate: Determines if the user can navigate away from the current route.
  • CanActivateChild: Checks if a child route can be activated.
  • CanLoad: Determines if a lazy-loaded module should be loaded.
  • Resolve: Fetches data before a route is activated.

2. Route guards and lazy loading
By loading modules only when necessary, lazy loading is a crucial strategy for enhancing the efficiency of large Angular applications. Nevertheless, these advantages can be circumvented by using lazy-loaded modules in conjunction with route guards incorrectly.

Best Practices

  • Use CanLoad Instead of CanActivate for Lazy-Loaded Modules: The CanLoad guard prevents the entire module from loading if the guard returns false. This is more efficient than CanActivate, which loads the module but prevents activation if conditions aren’t met.
  • Preload Critical Modules: Use Angular's built-in preloading strategies, such as PreloadAllModules, to preload essential modules, ensuring quick access without sacrificing performance.

canLoad(route: Route): boolean {
  return this.authService.isLoggedIn();
}

3. Reducing Overhead in CanActivate Guards
CanActivate guards are commonly used to restrict access to routes based on user authentication or roles. However, performing complex logic or redundant checks in these guards can slow down navigation.

Best Practices

  • Cache User Permissions: Instead of fetching permissions from the server on each route change, cache them locally using services like NgRx or simple in-memory storage. Update the cache only when necessary (e.g., on login or role change).
  • Optimize Guard Logic: Ensure that the logic within your CanActivate guards is as efficient as possible. Avoid making unnecessary HTTP requests or performing complex calculations synchronously.
  • Asynchronous Guard Execution: Use asynchronous operations in guards only when necessary. When using Observable or Promise-based guards, ensure that they resolve quickly to avoid delays in route transitions.

canActivate(route: ActivatedRouteSnapshot): boolean {
  const requiredRole = route.data['role'];
  return this.authService.hasRole(requiredRole);
}


4. Enhancing Security with Role-Based Access Control (RBAC)Implementing RBAC within your route guards is a robust way to enforce security policies across your application. However, a poorly designed RBAC system can lead to security loopholes.Best Practices

  • Centralize Role Management: Manage user roles and permissions in a centralized service. This makes it easier to update and audit roles across your application.
  • Dynamic Role Assignment: Assign roles dynamically based on user data rather than hardcoding roles within your application. This allows for more flexible and maintainable access control.
  • Audit Route Guard Usage: Regularly audit your route guards to ensure that they are correctly implemented and up-to-date with your security policies. This helps prevent unauthorized access due to outdated or misconfigured guards.

canActivate(route: ActivatedRouteSnapshot): boolean {
  const requiredRoles = route.data['roles'] as Array<string>;
  return this.authService.hasAnyRole(requiredRoles);
}

5. Combining Multiple Guards Efficiently
In some cases, you may need to combine multiple guards for a single route. For example, you might want to check if a user is authenticated and if they have a specific role.

Best Practices
Use Composite Guards: Instead of chaining multiple guards, create composite guards that encapsulate all necessary checks. This reduces the overhead of multiple guard evaluations.

canActivate(route: ActivatedRouteSnapshot): boolean {
  return this.authService.isLoggedIn() && this.authService.hasRole('admin');
}


Order Guards for Efficiency: If you must use multiple guards, order them from least to most computationally expensive. This ensures that simple checks are performed first, potentially bypassing more complex checks if they fail.
const routes: Routes = [
  {
    path: 'admin',
    canActivate: [AuthGuard, RoleGuard],
    component: AdminComponent
  }
];


6. Debugging and Testing Route Guards
Even with optimizations, route guards can introduce issues if not thoroughly tested and debugged.

Best Practices

  • Unit Testing Guards: Write unit tests for your route guards to ensure they behave as expected under various conditions. Use Angular's TestBed to create isolated tests for each guard.
  • Logging and Monitoring: Implement logging within your guards to monitor their execution in production. This can help identify performance bottlenecks or security issues that may arise.
  • Profiling Route Guards: Use Angular’s built-in profiling tools or browser developer tools to measure the performance impact of your route guards. Optimize any guards that are identified as slow or resource-intensive.

it('should allow the authenticated user to access route', () => {
  authService.isLoggedIn.and.returnValue(true);
  expect(guard.canActivate()).toBe(true);
});

Conclusion
Optimizing Angular route guards for performance and security requires a deep understanding of Angular’s routing system and careful consideration of best practices. By implementing lazy loading strategies, reducing overhead in guard logic, enhancing security with RBAC, and efficiently combining multiple guards, you can ensure that your Angular application is both fast and secure.



AngularJS Hosting Europe - HostForLIFE.eu :: Data Exchange between Parents and Children in Angular 18

clock August 28, 2024 09:59 by author Peter

You will discover the solutions to the following questions and how to transfer/share data from the child component to the parent component in this walkthrough.

  • @Output: What is it?
  • An Event Emitter: What Is It?

What is @Output?
@Output decorator is used to share the data from the child component to the parent component.

What is an event emitter?

An event emitter is used to create custom events for AngularComponent. Mainly, the event emitter is used to pass data from a child component to a parent component using the @output decorator.

In short, sending data to the parent is publishing /emitting the vent, and the parent component listens the same.

Send Data from Child to Parent Component
Create an Angular Project called “AnguWalk” using the following CLI command.

Command
ng new AnguWalk

Example

Move the cursor to inside the project folder and open Visual Studio code.

Command
cd anguwalk <enter>
code . <enter>


Example

Note. Visual studio code will get started only if your system is configured with path and settings.
Now, we are going to Create a child component to issue the default city value.

Command
ng g c childdefacity

Open the childdefacity.component.ts file and update the following code.
import { Component, EventEmitter, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-childdefacity',
  standalone: true,
  imports: [],
  templateUrl: './childdefacity.component.html',
  styleUrls: ['./childdefacity.component.css']
})
export class ChilddefacityComponent implements OnInit {
  defaultcity: string = "Shirdi";
  @Output() updatecity = new EventEmitter<string>();
  ngOnInit(): void {}
  SendToParent() {
    this.updatecity.emit(this.defaultcity);
  }
}


Open the childdefacity.component.html file and update the following code.
<p>Child Component Content --> childdefacity works!</p>
<button type="button" style="font-size: xx-large;" (click)="SendToParent()">Send Default City</button>


Open the app.component.ts file and update the following code.
import { Component, NgModule, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { ChilddefacityComponent } from './childdefacity/childdefacity.component';
declare function HelloMsg(arg: any): void;
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, FormsModule, CommonModule, ChilddefacityComponent],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  parentdefacity: string = '';
  txtFullname: string = '';
  txtCityname: string = '';

  getdata(defacity: string) {
    this.txtCityname = defacity;
    // alert(this.txtCityname);
  }
  formpro(form: any) {
    alert('submit');
    console.log(form);
    console.log(this.txtCityname);
    console.log(this.txtFullname);
  }
}

Open the app.component.ts file and update the following code.
import { Component, NgModule, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { ChilddefacityComponent } from './childdefacity/childdefacity.component';
declare function HelloMsg(arg: any): void;
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, FormsModule, CommonModule, ChilddefacityComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  parentdefacity: string = "";
  txtFullname: string = "";
  txtCityname: string = "";

  getdata(defacity: string) {
    this.txtCityname = defacity;
    // alert(this.txtCityname);
  }
  formpro(form: any) {
    alert("submit");
    console.log(form);
    console.log(this.txtCityname);
    console.log(this.txtFullname);
  }
}


Open the app.component.html file and update the following code.
<router-outlet />

<form #contForm="ngForm" (ngSubmit)="formpro(contForm.value)">
  <table>
    <tr>
      <td>Fullname</td>
      <td>
        <input
          type="text"
          id="txtFullname"
          style="font-size: xx-large;"
          name="txtFullname"
          [(ngModel)]="txtFullname">
      </td>
    </tr>

    <tr>
      <td>City</td>
      <td>
        <input
          type="text"
          id="txtCity"
          style="font-size: xx-large;"
          name="txtCity"
          [(ngModel)]="txtCityname">
      </td>
    </tr>

    <tr>
      <td colspan="2">
        <app-childdefacity (updatecity)="getdata($event)"></app-childdefacity>
      </td>
    </tr>

    <tr>
      <td colspan="2">
        <button type="submit" style="font-size: xx-large;">Submit</button>
      </td>
    </tr>
  </table>
</form>


OUTPUT

 



AngularJS Hosting Europe - HostForLIFE.eu :: Knowing Angular vs. React

clock August 19, 2024 10:05 by author Peter

React and Angular are two of the most widely used front-end frameworks for creating contemporary online apps. Both are supported by sizable groups and have distinct advantages, yet they serve varying needs and tastes. We'll go over the main distinctions between Angular and React in this post to assist you in choosing the right framework for your project.

Overview

  1. React
    • Developed by: Facebook
    • Initial Release: 2013
    • Type: JavaScript library for building user interfaces, primarily focused on rendering UI components.
    • Learning Curve: Moderate
    • Main Concept: React is centered around components and follows a unidirectional data flow.
  2. Angular
    • Developed by: Google
    • Initial Release: 2016 (as Angular 2, the complete rewrite of AngularJS)
    • Type: Full-fledged framework for building web applications.
    • Learning Curve: Steep
    • Main Concept: Angular is an opinionated framework that provides a comprehensive solution for building large-scale applications, including built-in features like routing, state management, and HTTP services.

Architecture

  1. React
    • Component-Based: React is all about components. Each piece of UI is a component that can manage its state and be reused throughout the application.
    • Virtual DOM: React uses a virtual DOM to optimize rendering performance. When the state of a component changes, React updates the virtual DOM and then efficiently updates the real DOM.
    • Flexibility: React offers flexibility by allowing developers to choose their own libraries for routing, state management, and other needs. This makes React a "view library" rather than a full-fledged framework.
  2. Angular
    • MVC Architecture: Angular follows the Model-View-Controller (MVC) pattern, which helps in separating the concerns of data (Model), UI (View), and logic (Controller).
    • Real DOM: Unlike React, Angular directly interacts with the real DOM, which can impact performance in complex applications. However, Angular mitigates this with its change detection mechanism.
    • Built-In Features: Angular comes with a range of built-in features like form validation, HTTP client, routing, and RxJS for reactive programming. This makes Angular a complete solution for building applications without relying on external libraries.

Performance

  1. React
    • Virtual DOM: React’s virtual DOM significantly improves performance by minimizing the number of direct manipulations to the real DOM.
    • Component Reusability: React’s component-based architecture promotes reusability, which can lead to better performance in large applications.
    • Bundle Size: React itself is relatively lightweight, but depending on the additional libraries you use, the bundle size can grow.
  2. Angular
    • Change Detection: Angular’s change detection mechanism can sometimes lead to performance bottlenecks in large applications, but it also provides tools like OnPush strategy and NgZone to optimize performance.
    • Ahead-of-Time (AOT) Compilation: Angular’s AOT compilation improves performance by compiling the application during the build process, reducing the load time.
    • Built-In Features: While Angular’s rich feature set can impact performance, the framework’s ability to optimize these features mitigates the impact.

Learning Curve

  1. React
    • JSX: React uses JSX, a syntax extension that allows you to write HTML within JavaScript. While some developers find JSX intuitive, others might find it challenging initially.
    • Flexibility: React’s flexibility means you need to learn how to integrate and use various libraries for routing, state management, etc., which can be both an advantage and a challenge.
    • Documentation and Community: React has extensive documentation and a large community, making it easier to find resources, tutorials, and third-party libraries.
  2. Angular
    • Steep Learning Curve: Angular has a steeper learning curve due to its complexity and the number of built-in features you need to understand.
    • TypeScript: Angular is built with TypeScript, a statically typed superset of JavaScript. While this adds benefits like better tooling and error checking, it also requires learning TypeScript if you’re not already familiar with it.
    • Comprehensive Framework: Angular’s opinionated nature means that once you learn the Angular way of doing things, you have a powerful set of tools at your disposal.

Ecosystem and Community

  1. React
    • Ecosystem: React has a rich ecosystem with numerous libraries for state management (Redux, MobX), routing (React Router), and more. The flexibility to choose different tools gives developers more control over their stack.
    • Community: React has a large and active community, contributing to a vast array of plugins, tools, and resources.
  2. Angular
    • Ecosystem: Angular has a more integrated ecosystem. Many features that require third-party libraries in React are built into Angular, such as routing, HTTP services, and form handling.
    • Community: Angular also has a large community, but it is more centralized around the official Angular resources, documentation, and Google-backed initiatives.

Use Case
React

  1. When to Use React
    • You need flexibility in choosing libraries and tools.
    • You prefer a simple, component-based architecture.
    • You are building a project where performance and simplicity are key.
  2. Popular Use Cases
    • Single-page applications (SPAs)
    • Static sites with dynamic components
    • Dashboards and data visualization tools

Angular

  1. When to Use Angular
    • You are building a large-scale, enterprise-level application.
    • You need a framework with a comprehensive set of tools and built-in features.
    • You prefer an opinionated framework that guides architectural decisions.
  2. Popular Use Cases
    • Complex, enterprise-level applications
    • Applications requiring robust form handling and validation
    • Real-time applications with complex state management

Conclusion
The skills of your team and the needs of your project will determine which of React and Angular is best. React is an excellent option for projects where you want more control over the architecture because of its simplicity and versatility. In contrast, Angular offers a feature-rich, opinionated framework right out of the box, making it perfect for enterprise-level apps.

Both Angular and React are effective front-end development tools, and knowing the advantages and disadvantages of each will help you choose wisely for your upcoming project.




AngularJS Hosting Europe - HostForLIFE.eu :: Study Angular's Component Routing

clock August 14, 2024 07:19 by author Peter

In Angular, component routing is usually done via the Router service. This allows you to call or go to a component from another component. Here's how you can make this happen. In the Router Module, define routes. The first step is to configure your routes in your AppRoutingModule (or any other defined routing module). Describe the pathways and the matching parts.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ComponentA } from './component-a/component-a.component';
import { ComponentB } from './component-b/component-b.component';

const routes: Routes = [
  { path: 'component-a', component: ComponentA },
  { path: 'component-b', component: ComponentB },
  // Add more routes as needed
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Use RouterLink in Templates
You can navigate to another component using the RouterLink directive in your template (HTML) of the first component.
<!-- component-a.component.html -->
<a [routerLink]="['/component-b']">Go to Component B</a>

Navigate Programmatically Using the Router
You can also navigate programmatically using the Angular Router in your component's TypeScript file.
import { Component } from '@angular/core';
import { Router } from '@angular/router';

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

  constructor(private router: Router) { }

  goToComponentB() {
    this.router.navigate(['/component-b']);
  }
}


In HTML template
<!-- component-a.component.html -->
<button (click)="goToComponentB()">Go to Component B</button>


Outlet to Render Routed Components
Ensure you have a <router-outlet></router-outlet> in your main HTML template (e.g., app.component.html) where the routed components will be displayed.
<!-- app.component.html -->
<router-outlet></router-outlet>


Lazy Loading (Optional)
If you want to load a module lazily, define your route like this.
const routes: Routes = [
  {
    path: 'component-b',
    loadChildren: () =>
      import('./component-b/component-b.module')
        .then(m => m.ComponentBModule)
  }
];


Summary

  • RouterLink: For navigation within the template.
  • Router.navigate: For programmatic navigation within the component's TypeScript file.
  • Router Outlet: Acts as a placeholder in the template where routed components are displayed.


This setup allows you to call or navigate between components effectively in Angular.



AngularJS Hosting Europe - HostForLIFE.eu :: Enhancing Angular Efficiency With The @defer Directive

clock August 6, 2024 06:57 by author Peter

Increasing the speed and smoothness of an application requires performance tuning. To aid in this, Angular, a well-liked framework for creating online applications, has introduced the @defer directive. Both load times and user experience are enhanced. We'll explain the @defer directive, its operation, and how you can use it to improve your Angular apps in this blog post.

@defer: What is it?

Using an Angular condition, the @defer directive allows you to load specific portions of a template only when needed. This can improve the efficiency of your program by only rendering components when required. For instance, it can load and display material only after the user presses a button or until a certain portion of the screen is visible. In this manner, your software loads faster and more effectively because it just loads what is needed.

Syntax
@defer () {
} @placeholder () {
} @loading () {
} @error {
}


@defer Directive
This is used to delay the loading of a template fragment until certain conditions are met.
on <trigger>: Specifies an event that triggers the deferred loading. Here is one simple example of on viewport trigger

@defer (on viewport) {
  <component />
}

(on viewport) specifies that the deferred rendering should happen when the element comes into the viewport.

when <condition>: Defines the condition that needs to be true before the template is loaded.
prefetch on <trigger>: Optionally, you can prefetch the content based on a trigger.
prefetch when <condition>: Optionally, you can prefetch the content when a certain condition is true.

@placeholder Directive
This defines what should be shown while the deferred content is being loaded.

@loading Directive

This defines the content to be shown while the deferred content is actually loading.

@error Directive

This defines what should be shown if there's an error during the loading process.

In short, this syntax lets you control when different parts of your Angular template appear and what to show while you’re waiting, depending on different conditions and triggers.

Benefits of Using @defer directive

  • Faster Loading: By delaying less important content, your app loads quicker and feels smoother to use.
  • Better User Experience: Users see the key parts of your app right away, while the less important stuff loads in the background, so the app stays responsive.
  • Efficient Use of Resources: By waiting to display parts of your app that aren’t needed right away, you free up your browser’s resources, making everything run more smoothly.


Summary

The @defer directive in Angular helps make your app run better and faster. It allows you to delay loading some parts of your app until they're really needed. This way, your app stays quick and responsive, even if it has a lot of data or complex tasks. Using @defer can make your app perform better and provide a smoother experience for users.

Please let me know in the comments area if you have any questions.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in