Angular2:将所有属性传递给子组件

Angular2: passing ALL the attributes to the child component

甚至不知道解释这个问题的正确术语

所以,想象一下这个场景...

有一个表单输入组件并捕获一些属性并将其传递给内部的标记

<form-input placeholder="Enter your name" label="First name" [(ngModel)]="name" ngDefaultControl></form-input>

所以,这是标记,希望是不言自明的...

很明显我有

  @Input() label: string = '';
  @Input() placeholder: string = '';

然后在视图中我有这些行

<div class="form-group">
    <label>{{label}}
    <input type="text" [placeholder]="placeholder" [(ngModel)] = "ngModel">
</div>

现在,到目前为止一切正常...

但是假设我想在它周围添加验证规则... 或者添加我没有通过 @Input()

捕获的其他属性

如何在视图中将来自 <form-input> 的任何其他内容传递给我的 <input>

您可以迭代组件的 DOM 属性:

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)
  }
}

对于懒惰的人:

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 将不起作用,因为 ngAfterViewInit 将在外部元素之前为内部元素调用。 IE。内部组件将在从外部组件接收属性之前传递其属性,因此最内部的元素不会从最外部的元素接收属性。这就是我在这里使用 ngOnInit 的原因。