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>