Angular2: passing ALL the attributes to the child component

For the lazy ones:

export class FormInput implements OnInit {
  @ViewChild(NgModel, {read: ElementRef}) inpElementRef: ElementRef;

  constructor(
    private elementRef: ElementRef
  ) {}
  
  ngOnInit() {
    const attributes = this.elementRef.nativeElement.attributes;
    const inpAttributes = this.inpElementRef.nativeElement.attributes;
    for (let i = 0; i < attributes.length; ++i) {
      let attribute = attributes.item(i);
      if (attribute.name === 'ngModel' ||
        inpAttributes.getNamedItemNS(attribute.namespaceURI, attribute.name)
      ) {
        continue;
      }
      this.inpElementRef.nativeElement.setAttributeNS(attribute.namespaceURI, attribute.name, attribute.value);
    }
  }
}

ngAfterViewInit won't work if you nest multiple components which pass attributes, because ngAfterViewInit will be called for inner elements before outer elements. I.e. the inner component will pass its attributes before it received attributes from the outer component, so the inner most element won't receive the attributes from the outer most element. That's why I'm using ngOnInit here.


You could iterate on the DOM attributes of your component :

import { ElementRef } from '@angular/core';
...

export class FormInput {
  constructor(el: ElementRef) {
    // Iterate here over el.nativeElement.attributes
    // and add them to you child element (input)
  }
}