Angular2在带有指令的标记中插入自定义属性

时间:2017-06-21 08:49:41

标签: angular attributes tags element directive

我有一个角度2项目,我正在使用PrimeNG。 我正在使用具有许多自定义属性的特殊标记,并且这些属性对于此标记始终是相同的。 我想外化这些属性,我创建了一个自定义指令,用于添加我需要的所有属性。 问题是这些属性中的一些不是原生的,也许它们不被识别。我在“元素”上收到错误“无法执行'setAttribute':'[myCustomAttribute]'不是有效的属性名称。

这是我的指示:

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

  constructor(private _elRef: ElementRef, private _renderer: Renderer2) {
  }

  ngOnInit() {
    this._renderer.setAttribute(this._elRef.nativeElement, '[yearRange]', '1900:2100');
  }
}

任何人都知道如何解决它? 我不知道是否有办法复制字符串等元素并操纵添加我的属性的字符串。

由于 的Fabrizio

3 个答案:

答案 0 :(得分:1)

您无法使用renderer.setAttribute(...)设置不属于您正在使用的原生HTML元素的属性。
对于任何原生HTML元素,yearRange甚至都不是准确的属性。它应该被声明为指令类中的输入,以便正确设置它的值:

@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 :(得分:1)

这可能对您有用。 Angular2 add attribute with Renderer using a directive

我认为年度之间的方括号是罪魁祸首。希望这会有所帮助。

答案 2 :(得分:0)

我们可以使用 Renderer2 类的 setAttribute 方法

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");
      }
    }
相关问题