3

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?

3
  • Try ngAfterViewInit instead of ngOnInit Commented Mar 20, 2018 at 17:25
  • Is the formControlName attribute present on the tag when you inspect it in your Browser ? By the way, maybe you should use the correct way to get the attribute. Commented Mar 20, 2018 at 17:31
  • It is. Yeah, I think that's was what I asking. See my answer. Commented Mar 20, 2018 at 17:43

2 Answers 2

5

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>
Sign up to request clarification or add additional context in comments.

Comments

0

A hack, but a possibly useful side note:

This works from ngOnInit:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.