I have an angular 2 project and I'm using PrimeNG. I'm using a special tag with a lot of custom attributes and these attributes are always the same for this tag. I want to externalize these attributes and I created a custom directive used to add all attributes I need. The problem is that some of these attributes aren't native and maybe they aren't recognized. I get the error "Failed to execute 'setAttribute' on 'Element': '[myCustomAttribute]' is not a valid attribute name.
This is my directive:
@Directive({
selector: '[def-calendar]'
})
export class DefaultCalendarDirective {
constructor(private _elRef: ElementRef, private _renderer: Renderer2) {
}
ngOnInit() {
this._renderer.setAttribute(this._elRef.nativeElement, '[yearRange]', '1900:2100');
}
}
Anyone know how can I fix it? I don't know if is there a way to copy the element such as string and manipulate the string adding my attributes.
Thanks Fabrizio
This might be useful for you. Angular2 add attribute with Renderer using a directive.
I think the square bracket between the yearRange is the culprit. Hope this helps.
You can't use renderer.setAttribute(...)
to set attributes that don't belong to the native HTML element you're using.yearRange
isn't even an attribute to be accurate for any native HTML element. It should be declared as an input in class of the directive in order to set values for it properly:
@Directive({
selector: '[def-calendar]'
})
export class DefaultCalendarDirective implements OnInit {
@Input() yearRange: string = '1900:2100';
constructor() {
}
public ngOnInit() {}
}
You can also change the input value by passing it a string (or you can also use binding instead) when you're using the directive on an element.
<someElement def-calendar yearRange="1900:2100"></someElement>
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