Angular2 add custom attribute to tag with directive

I have an angular 2 project and am using PrimeNG. I use 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 the attributes I need. The problem is that some of these attributes are not native and may not be recognized. I get the error "Failed to execute" setAttribute "in" 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');
  }
}
Run codeHide result

- , ? , , , , .

+4
3

renderer.setAttribute(...) , HTML-, .
yearRange , HTML. , :

@Directive({
  selector: '[def-calendar]'
})
export class DefaultCalendarDirective implements OnInit {

  @Input() yearRange: string = '1900:2100';

  constructor() {
  }

  public ngOnInit() {}
}

, ( ), .

<someElement def-calendar yearRange="1900:2100"></someElement>
+1

. Angular2 Renderer .

, yearRange . , .

+1

setAttribute Renderer2

import {Directive, ElementRef, Renderer2, Input, HostListener} from '@angular/core';

@Directive({
  selector: '[DirectiveName]'
})
export class DirectiveNameDirective {
 constructor(public renderer : Renderer2,public hostElement: ElementRef){}
ngOnInit() {
      this.renderer.setAttribute(this.hostElement.nativeElement, "data-name", "testname");
      }
    }
0

Source: https://habr.com/ru/post/1679785/


All Articles