Skip to content

Instantly share code, notes, and snippets.

@hartraft
Last active November 3, 2017 10:38
Show Gist options
  • Save hartraft/604d1fdc2c3cf07f6d85e3ae639fda13 to your computer and use it in GitHub Desktop.
Save hartraft/604d1fdc2c3cf07f6d85e3ae639fda13 to your computer and use it in GitHub Desktop.
Minimal Angular 4+ Attribute Directive binding to @input property based on Angular docs https://angular.io/guide/attribute-directives
import { Directive, ElementRef, Renderer2, Input, OnInit } from '@angular/core';
@Directive({ selector: '[attrDirective]' })
export class AttributeDirective {
@Input('statusField') statusField: string;
constructor(private el: ElementRef, private renderer: Renderer2) { // use Renderer2 as Renderer is deprecated
this.renderer.addClass(el.nativeElement, 'label'); // add Bootstrap label classes. need to access the nativeElement
}
// @Input properties only available onInit
ngOnInit(): void {
if (this.statusField.toUpperCase() === 'SUCCESS') {
this.renderer.addClass(el.nativeElement, 'label-success');
}
// change inner text to status
this.renderer.setProperty(this.el.nativeElement, 'innerHTML', this.statusField);
this.renderer.setStyle(this.el.nativeElement, 'text-transform', 'uppercase');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment