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

DS_*_*per 8 javascript angular2-forms angular

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

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

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

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

所以,这是标记,希望是非常自我解释的......

显然在我有

  @Input() label: string = '';
  @Input() placeholder: string = '';
Run Code Online (Sandbox Code Playgroud)

然后在视图中我有一些东西沿着这些线

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

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

但是,假设我想在它周围添加验证规则......或者添加我不通过其捕获的其他属性 @Input()

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

fis*_*one 5

对于懒人:

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ngAfterViewInit如果嵌套多个传递属性的组件将不起作用,因为ngAfterViewInit将在外部元素之前调用内部元素。即内部组件将在从外部组件接收属性之前传递其属性,因此最里面的元素不会从最外面的元素接收属性。这就是我在ngOnInit这里使用的原因。