I have a directive which I want to use to add dynamically attributes to input fields. Which works, it adds the correct attribute to the input field. But the directive for that attribute doesn't work. So I think I need to compile it, in the new Angular there is no compile.
So I used Renderer2
, but it still doesn't work.
The directive to add dynamically attributes:
import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[addAttributes]'
})
export class addAttributesDirective implements OnInit {
@Input() attributes: any;
constructor(private renderer: Renderer2, private el: ElementRef) {}
ngOnInit() {
this.addAttributes();
}
addAttributes() {
const mapping: any = {
FieldUppercase: 'uppercase'
};
this.attributes.forEach((attr: any) => {
const attribute = mapping[attr];
if (attribute) {
this.renderer.setAttribute(this.el.nativeElement, attribute, 'true');
}
});
this.el.nativeElement.removeAttribute('addAttributes');
}
}
So when I use:
<input type="text"
[name]="id"
[id]="id"
class="form-control"
[ngModel]="value"
[attributes]="attributes"
addAttributes />
It adds uppercase="true"
to the input field, which is correct.
But the directive for uppercase doesn't work.
Directive uppercase:
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[uppercase]'
})
export class UppercaseDirective implements OnInit {
@Input() attributes: any;
constructor(private el: ElementRef) {
}
ngOnInit() {
console.log('uppercase');
}
}
Normally I need to see uppercase
in the console log, but that's not working.
What am I doing wrong?
I can't use pipes in certain situations so want to do it like this.