Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 insert custom attribute in tag with directive

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

like image 364
Fabrizio P Avatar asked Jun 21 '17 08:06

Fabrizio P


Video Answer


2 Answers

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.

like image 156
grey.dim Avatar answered Oct 20 '22 13:10

grey.dim


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>
like image 43
Unsinkable Sam Avatar answered Oct 20 '22 11:10

Unsinkable Sam