【问题标题】:Read/get element attribute from within custom directive in Angular 2+从Angular 2+的自定义指令中读取/获取元素属性
【发布时间】:2018-03-20 17:14:39
【问题描述】:

我正在构建一个自定义指令,我想在其中读取本机元素的一个属性 (formControlName),然后有条件地向该元素添加一个或多个属性。

但是,当我 console.log 原生元素的属性时,我得到:

未定义

这是我尝试过的:

@Directive({
  selector: '[appInputMod]'
})
export class InputModDirective implements OnInit {

  constructor(public renderer: Renderer2, public hostElement: ElementRef) { }

  @Input()
  appInputMod() { }

  ngOnInit() {

    console.log(this.hostElement.nativeElement.formcontrolname);

    const el = this.hostElement.nativeElement;
    if (el.formcontrolname === 'firstName')
    {
        this.renderer.setAttribute(this.hostElement.nativeElement, 'maxlength', '35');
    }
  }
}

如何从指令中读取此属性名称?

【问题讨论】:

  • 试试ngAfterViewInit 而不是ngOnInit
  • 我得到了同样的结果。
  • 当您在浏览器中检查标签时,标签上是否存在 formControlName 属性?顺便说一句,也许你应该使用正确的方式来获取属性。
  • 是的。是的,我想这就是我要问的。看我的回答。

标签: angular angular2-directives


【解决方案1】:

你所做的似乎不是很 Angular,你通常不想开始依赖 DOM 操作。更 Angular 的方法是将指令元素上的属性读取为 @Input(),并将结果作为 @Output() 提供:

@Directive({
  selector: '[appInputMod]'
})
export class InputModDirective implements OnInit {
  @Input() formcontrolname: string;
  @Output() somethingHappened: EventEmitter<any> = new EventEmitter<any>();

  constructor(public renderer: Renderer2, public hostElement: ElementRef) { }

  ngOnInit() {
    if (formcontrolname === 'firstName') {
      this.somethingHappened.emit({maxlength: 35});
    }

然后在你的模板中:

<some-element appInputMod formcontrolname="myName" (somethingHappened)="doSomething($event)">
</some-element>

【讨论】:

    【解决方案2】:

    一个 hack,但可能有用的旁注:

    这适用于 ngOnInit:

    this.hostElement.nativeElement.getAttribute('formcontrolname');
    

    【讨论】:

      猜你喜欢
      • 2016-05-13
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多