Angular – Custom attribute directive – Examples

Angular

Angular directives are classes that can add new behavior to the elements in the template or modify existing behavior.

Example #1

directive.ts

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[directiveDemo]'
})
export class DemoDirective {

  @Input() directiveDemo: string = "";

  constructor() { }

  ngOnInit() {
    console.log(this.directiveDemo);
  }

}

component.html

<div [directiveDemo]="'Directive value'">Directive 1</div>

Example #2

directive.ts

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[directiveDemo]'
})
export class DemoDirective {

  @Input() myAttr1: string = "";
  @Input() myAttr2: number = 0;
  @Input() myAttr3: string = "0";

  constructor() { }

  ngOnInit() {
    console.log(this.myAttr1)
    console.log(this.myAttr2)
    console.log(this.myAttr3)
  }

}

component.html

<div
  directiveDemo
  [myAttr1]="'My atttribute 1'"
  [myAttr2]="2"
  myAttr3="3"
>
  Directive 1
</div>

Example #3

directive.ts

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[directiveDemo]'
})
export class DemoDirective {

  @Input() directiveDemo: string = "";
  @Input() myAttr1: string = "";
  @Input() myAttr2: number = 0;
  @Input() myAttr3: string = "0";

  constructor() { }

  ngOnInit() {
    console.log(this.directiveDemo);
    console.log(this.myAttr1)
    console.log(this.myAttr2)
    console.log(this.myAttr3)
  }

}

component.html


<div
  directiveDemo="Directive value"
  [myAttr1]="'My atttribute 1'"
  [myAttr2]="2"
  myAttr3="3"
>
  Directive 1
</div>
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *