Title: angular4 directive not working inside HTML SPAN tag
Tags: html;angular
Question: I have written a directive in angular4, which works on input fields.
When I apply that on SPAN tag, it is not working.
Can we apply the directives on SPAN TAG, or is there any work around.
<span dirTemp&gt;45789</span&gt;
dirTemp actually corrects the value to 45,789
import { Directive, HostListener, ElementRef, OnInit, AfterViewInit, AfterViewChecked, AfterContentChecked } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[dirTemp ]',
export class FormatterDirective implements AfterViewChecked {
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private cPipe: MyPipe
this.el = this.elementRef.nativeElement;
// ngOnInit() {
//  this.el.value = this.cPipe.transform(this.el.value);
// }
ngAfterViewChecked(): void {
this.el.value = this.cPipe.parse(this.el.value);
this.el.value = this.cPipe.transform(this.el.value);
@HostListener('focus', ['$event.target.value'])
onFocus(value) {
console.log('in formatter directive:', value);
this.el.value = this.cPipe.parse(value);
@HostListener('focusout', ['$event.target.value'])
onFocusout(value) {
this.el.value = this.cPipe.transform(value);
Comment: A span doesn't fire `focusout` by default. You should post your html structure to get more context on what you are trying to do

Comment: I added my  directive, may be I need to add another hostlistener. I am apply the directive to a column in the table. The TD value is inside

Comment: @Pierre, ok. My html is very simple, In a table, I have   45789

Comment: Can you please add some code so we could help you out better?


Here is another answer: Workaround: span doesn't have value but has innerText or innerHTML. So, On ngOnInit you can do:
ngOnInit() {
if(this.el.tagName.toUpperCase() !== 'INPUT') {
//  Apply your tranform here:
var originalValue =  this.el.innerText;
this.el.innerText = this.cPipe.transform(originalValue);
Comment for this answer: @user1015388 You have that defined in your constructor. `this.el = this.elementRef.nativeElement;`
Comment for this answer: I tried to use this, this.el.innerText gives empty value
Comment for this answer: Yes, I figured out that my value with in SPAN TAG is dynamic with in {{}}. SO its empty. How can we get tat
Comment for this answer: I need to use afterviewchecked, as my data renders after the view is complete. Thanks

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:07/17/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<html><angular>', 'Title': 'angular4 directive not working inside HTML SPAN tag', 'ViewCount': 658, 'id': 51384581, 'user_AboutMe': None, 'user_AccountId': 1000404.0, 'user_DisplayName': 'user1015388', 'user_Reputation': 1221.0, 'user_Views': 236.0, 'user_id': 1015388.0}}