1

I have created a simple Angular directive where I control whether an element will be shown or not. What I am unable to perform is the following:

  1. Modify an attribute of the element where this directive is used
  2. Add an html element to the same element

@Directive({
  selector: '[needPermission]'
})
export class NeedPermissionDirective {
  private visible = true;

  constructor(private templateRef: TemplateRef < any > , private viewContainer: ViewContainerRef) {}

  @Input() set needPermission(permissionId: string) {
    if (this.visible === true) {
      // TODO-1: Modify an attribute for an element within the templateRef
      // TODO-2: Add an html element to the templateRef like a <div>        
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }

  })
}
}
Georgios Stathis
  • 533
  • 1
  • 6
  • 21

1 Answers1

0

here's an example to modify attributes

import { AfterViewInit, Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[imgError]'
})
export class ImgErrorDirective implements AfterViewInit {

  constructor(private _elRef: ElementRef, private _renderer: Renderer2) { }

  ngAfterViewInit(){
    try{
      this._elRef.nativeElement.childNodes[0].childNodes[0]
        .childNodes[0].childNodes[0].childNodes
        .forEach((child: any)=>{
           this._renderer.setAttribute(child.childNodes[0]
             .childNodes[0].childNodes[0], 'onerror', "this.src='assets/img/no- 
               photo.jpg'");
      });
    }catch{}
  }
}

In this example, I am looping a childNodes list containing img and modifying the onerror attribute of each.

Ghaith Troudi
  • 248
  • 1
  • 8