The following directive should hide an element.
import {Directive, ElementRef, Input, Renderer2} from '@angular/core';
import {el} from "@angular/platform-browser/testing/src/browser_util";
// Directive decorator
@Directive({ selector: '[hide-me]' })
// Directive class
export class MyHiddenDirective {
// @Input() hideme:boolean;
constructor(public el: ElementRef, public renderer: Renderer2) {
// Use renderer to render the element with styles
renderer.setStyle(el.nativeElement, 'display', 'none');
}
}
I am using it as follows:
<div>Name: <input hide-me #myint type="text" name="name" [(ngModel)]="this.name" /> You entered {{this.name}} {{myint.hasAttribute('required')}}</div>
Why does selector: '[hide-me]' work but selector: 'hide-me' doesn't? I do not use square brackes when I use the Directive <input hide-me... and not <input [hide-me].... In Components, we generally specify selector without square brackets. Why do I need to specify square brackets in Directives?
Because the selector is a CSS selector. The same kind of selector you use in a CSS file to specify which elements are concerned by a CSS rule:
foo means elements with name foo[foo] means elements with an attribute named foo.foo means elements with a CSS class named foofoo[bar] means elements named foo with an attribute named bar, etc.As a complement
The directive's selector can be used as an input which is especially useful when that input carries something other than a boolean (as the directive instance suffices to tell it is active), use the @Input decorator's "bindingPropertyName" argument to use distinct tokens between the template attribute and the Directive class property:
@Directive({ selector: '[enhanced-me]' })
export class NodeEnhancementDirective {
@Input('enhanced-me') options: {foo: true, bar: true} ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With