BBaysinger
BBaysinger

Reputation: 6987

Read/get element attribute from within custom directive in Angular 2+

I'm building a custom directive where I want to read one of the attributes (formControlName) of the native element, and then conditionally add one or more attributes to the element.

However, when I console.log the native element's attribute, I get:

undefined

Here's what I tried:

@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');
    }
  }
}

How can I read this attribute name from within the directive?

Upvotes: 3

Views: 7336

Answers (2)

Robin De Schepper
Robin De Schepper

Reputation: 6365

What you're doing doesn't seem very Angular, you normally don't want to start relying on DOM manipulation. The more Angular approach would be to read the attribute on the element of your directive as an @Input(), and provide your results as an @Output():

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

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

And then in your template:

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

Upvotes: 5

BBaysinger
BBaysinger

Reputation: 6987

A hack, but a possibly useful side note:

This works from ngOnInit:

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

Upvotes: 0

Related Questions