angularangular2-directivesangular-directivecustom-directive

custom directive not working


I'm trying to create a directive for redacted/private information. If certain information is not provided a black box should be shown (as if the content was there but made invisible with a black box)

import { Directive, ElementRef, Renderer, OnInit } from 
'@angular/core';

@Directive({
selector: '[appRedactedContent]'
})
export class RedactedContentDirective implements OnInit {
min = 75;
max = 150;
width = this.randomIntFromInterval(this.min, this.max);
constructor(private el: ElementRef,
          private renderer: Renderer) {
          }
ngOnInit() {
  this.renderer.setElementStyle(
        this.el.nativeElement, 'background-color', 'blue !important');
        this.renderer.setElementStyle(this.el.nativeElement, 'width', 
                                      this.width.toString());
  }

randomIntFromInterval(min: number, max: number): number {
 return Math.floor(Math.random() * (max - min + 1) + min);
}
}

html

<a appRedactedContent></a>

I can see the style being added when I open my developer tools but the a-tag I can't see a blue box in my browser


Solution

  • the tag as a default display to inline, you cant enforce is width nor is height.

    As your a tag do not have a content it as a width of 0 and then you cant see it

    if you want to enforce the width, you have to set its display to inline-block

    ref to HTML specs