angular


 

Angular Directive

  • Directives are classes that add additional behavior to elements in Angular applications.
  • Use Angular's built-in directives to manage forms, lists, styles, and what users see.

Built-in directives


HELPFUL: Built-in directives use only public APIs. They do not have special access to any private APIs that other directives can't access.

The different types of Angular directives are as follows:

Directive TypesDetails
Components directives
  • Used with a template. This type of directive is the most common directive type.
Attribute directives
  • Change the appearance or behavior of an element, component, or another directive.
  • Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components.
  • The most common attribute directives are as follows:

    Common directivesDetails
    NgClassAdds and removes a set of CSS classes.
    NgStyleAdds and removes a set of HTML styles.
    NgModelAdds two-way data binding to an HTML form element.
Structural directives
  • Change the DOM layout by adding and removing DOM elements.
  • Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, and manipulating the host elements to which they are attached.
  • This section introduces the most common built-in structural directives:

    Common built-in structural directivesDetails
    NgIfConditionally creates or disposes of subviews from the template.
    NgForRepeat a node for each item in a list.
    NgSwitchA set of directives that switch among alternative views.


NgClass

  • Adds and removes CSS classes on an HTML element.
HELPFUL: To add or remove a single class, use class binding rather than NgClass.

Exported by

  • CommonModule

Description

Adds and removes CSS classes on an HTML element.

The CSS classes are updated as follows, depending on the type of the expression evaluation:

  • string - the CSS classes listed in the string (space delimited) are added,
  • Array - the CSS classes declared as Array elements are added,
  • Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.
E.g.
string: - [ngClass]="stringExp" eg. -> 
                we can use stringExp as string or stringExp=['btn', 'btn-search'] as string array 

Object: - [ngClass]="{'btn': true,' btn-search' : searchText, 'btn-search-desabiled': !searchText}"

expression: - [ngClass]="isSpecial ? 'special' : ''"

With a method: - 
.tc file
currentClasses: Record<string, boolean> = {};
...
  setCurrentClasses() {
    // CSS classes: added/removed per current state of component properties
    this.currentClasses = {
      saveable: this.canSave,
      modified: !this.isUnchanged,
      special: this.isSpecial,
    };
  }
.html
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>

For this use case, Angular applies the classes on initialization and in case of changes caused by reassigning the currentClasses object. The full example calls setCurrentClasses() initially with ngOnInit() when the user clicks on the Refresh currentClasses button. These steps are not necessary to implement ngClass.

class binding 

  • can create a CSS class binding to conditionally add or remove a CSS class on an element based on whether the bound value is truthy or falsy.
<!-- When `isExpanded` is truthy, add the `expanded` CSS class. -->
<ul [class.expanded]="isExpanded">

You can also bind directly to the class property. Angular accepts three types of value:

Description of class valueTypeScript type
A string containing one or more CSS classes separated by spacesstring
An array of CSS class stringsstring[]
An object where each property name is a CSS class name and each corresponding value determines whether that class is applied to the element, based on truthiness.Record<string, any>


@Component({  template: `    <ul [class]="listClasses"> ... </ul>    <section [class]="sectionClasses"> ... </section>    <button [class]="buttonClasses"> ... </button>  `,  ...})export class UserProfile {  listClasses = 'full-width outlined';  sectionClasses = ['expandable', 'elevated'];  buttonClasses = {    highlighted: true,    embiggened: false,  };}

The above example renders the following DOM:

<ul class="full-width outlined"> ... </ul><section class="expandable elevated"> ... </section><button class="highlighted"> ... </button>

Angular ignores any string values that are not valid CSS class names.

When using static CSS classes, directly binding class, and binding specific classes, Angular intelligently combines all of the classes in the rendered result.

@Component({  template: `<ul class="list" [class]="listType" [class.expanded]="isExpanded"> ...`,  ...})export class Listbox {  listType = 'box';  isExpanded = true;}

In the example above, Angular renders the ul element with all three CSS classes.

<ul class="list box expanded">

Angular does not guarantee any specific order of CSS classes on rendered elements.

When binding class to an array or an object, Angular compares the previous value to the current value with the triple-equals operator (===). You must create a new object or array instance when you modify these values in order for Angular to apply any updates.

If an element has multiple bindings for the same CSS class, Angular resolves collisions by following its style precedence order.


NgStyle

  • Adds and removes a set of HTML styles.
HELPFUL: To add or remove a single style, use style bindings rather than NgStyle.

Usage Notes

Set the width of the containing element to a pixel value returned by an expression.

<some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>

Set a collection of style values using an expression that returns key-value pairs.

<some-element [ngStyle]="objExp">...</some-element>

For more simple use cases you can use the style bindings directly. It doesn't require importing a directive.

Set the font of the containing element to the result of an expression.

<some-element [style]="{'font-style': styleExp}">...</some-element>

Use NgStyle to set multiple inline styles simultaneously, based on the state of the component.

  1. To use NgStyle, add a method to the component class.

  1. src/app/app.component.ts
      currentStyles: Record<string, string> = {};
    ...
    setCurrentStyles() { // CSS styles: set per current state of component properties this.currentStyles = { 'font-style': this.canSave ? 'italic' : 'normal', 'font-weight': !this.isUnchanged ? 'bold' : 'normal', 'font-size': this.isSpecial ? '24px' : '12px', }; }
  2. To set the element's styles, add an ngStyle property binding to currentStyles.

src/app/app.component.html
<div [ngStyle]="currentStyles">  This div is initially italic, normal weight, and extra large (24px).</div>


Custom directives

Attribute directives
--
  • Change the appearance or behavior of DOM elements and Angular components with attribute directives.

Building an attribute directive

This section walks you through creating a highlight directive that sets the background color of the host element to yellow. how to detect when a user mouses into or out of the element and to respond by setting or clearing the highlight color. walks you through setting the highlight color while applying the HighlightDirective.

  1. To create a directive, use the CLI command ng generate directive.

    ng generate directive highlight
  2. Import HostListener from '@angular/core'.

    src/app/highlight.directive.ts (imports)
    import {Directive, ElementRef, HostListener, inject} from '@angular/core';
  3. Add two event handlers that respond when the mouse enters or leaves, each with the @HostListener() decorator

  • The @Directive() decorator's configuration property specifies the directive's CSS attribute selector, [appHighlight].
  • Import ElementRef from @angular/coreElementRef grants direct access to the host DOM element through its nativeElement property.
  • HELPFUL: Directives do not support namespaces.
  • Subscribe to events of the DOM element that hosts an attribute directive, the <p> in this case, with the @HostListener() decorator.

    HELPFUL: The handlers delegate to a helper method, highlight(), that sets the color on the host DOM element, el.

src\app\highlight.directive.ts

import { Directive, ElementRef, HostListener, inject, Input, input } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  @Input('appHighlight') highlightColor: string = '';
  @Input() defaultColor = '';
  private el = inject(ElementRef);
  constructor() {}
  @HostListener('mouseenter') onMouseEnter(){
    this.highlight(this.highlightColor || this.defaultColor || 'red');
  }
  @HostListener('mouseleave') onMouseLeave(){
    this.highlight('');
  }
  private highlight(color: string){
    this.el.nativeElement.style.backgroundColor = color;
  }

}

src\app\app.component.ts

 imports: [FormsModule, CommonModule, HighlightDirective],

src\app\app.component.html

<p appHighlight ='red'>This is invalid</p>
<p appHighlight="lightblue">Hover over this text to see the highlight effect.</p>
<p appHighlight="pink">This text will highlight in pink on hover.</p>

<h2>pick a color</h2>
<div>
  <input type="radio" name="color" (click)="color='red'">red
  <input type="radio" name="color" (click)="color='green'">green
  <input type="radio" name="color" (click)="color='yellow'">yellow
</div>
<p [appHighlight]="color" defaultColor="pink">highlilte me!! {{color}}</p>


  • @Input() decorator adds metadata to the class that makes the directive's appHighlight property available for binding.

  • simultaneously apply the directive and the color, use property binding with the appHighlight directive selector, setting it equal to color.
  • [appHighlight] attribute binding performs two tasks:
    • Applies the highlighting directive to the  P tag element
    • Sets the directive's highlight color with a property binding












Comments

Popular posts from this blog