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

时间:2017-05-04 14:22:34

标签: javascript angular angular2-forms

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

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

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

中的标记
<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>

2 个答案:

答案 0 :(得分:2)

对于懒惰的人:

export class FormInput implements OnInit {
  @ViewChild(NgModel, {read: ElementRef}) inpElementRef: 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。即内部组件将在从外部组件接收属性之前传递其属性,因此,最内部的元素将不会从最外部的元素接收属性。这就是为什么我在这里使用ngOnInit的原因。

答案 1 :(得分:1)

您可以迭代组件的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)
  }
}
相关问题