Custom Attribute Directive
- Below is a Custom Attribute Directive which applies Background color to HTML Elements
- However we could not apply anylogic based on which directive would apply like checking row is even or odd
- Entry should be made in app.modules.ts for new directives created so it would be available
EvenrowHighlighterDirective.ts
import {AfterViewInit, Directive, ElementRef, OnInit} from '@angular/core'; @Directive({ selector: '[appevenrow]' }) export class EvenrowHighlighterDirective implements OnInit, AfterViewInit{ constructor(public elementRef: ElementRef) { } ngOnInit(): void { this.elementRef.nativeElement.style.backgroundColor = 'gray'; } ngAfterViewInit(){ //Add the above code here if ng-content and @child-content is used } }
Custom Structural Directive
- In below code we replace the functionality of ngIf using custom structural directive which checks for condition based on value set in isPresent
- Similar to ElementRef, TemplateRef gives access to template
- ViewContainer is a reference to the place where the Custom Structural Directive is placed
- One of the key thing while using structural directive is selector, @Input should have the same name. This reason behind this is due to the fact that *ngIf would be convered to ng-template before rendering.ng-template works on refernce basis within html. So when reference and directive name are different it would end up in error
test.component.ts
import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core'; @Directive({ selector: '[appDounless]' }) export class DounlessDirective { constructor(private templateRef: TemplateRef<any>, private vcRef: ViewContainerRef) { } @Input() set appDounless(condition: boolean){ if(condition) { this.vcRef.createEmbeddedView(this.templateRef); }else{ this.vcRef.clear(); } } }
test.component.ts
@Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class testComponent implements OnInit { public isPresent = true; ngOnInit() { } }
test.component.html
<p appevenrow> This is Custom Attribute Directive</p> <p *appDounless="isPresent">This is Custom Structural Directive</p>
Output