Custom Attribute Directive

  1. Below is a Custom Attribute Directive which applies Background color to HTML Elements
  2. However we could not apply anylogic based on which directive would apply like checking row is even or odd
  3. 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

  1. In below code we replace the functionality of ngIf using custom structural directive which checks for condition based on value set in isPresent
  2. Similar to ElementRef, TemplateRef gives access to template
  3. ViewContainer is a reference to the place where the Custom Structural Directive is placed
  4. 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

Comments are closed.