javascript - Angular 2 : passing ALL the attributes to the child component

标签 javascript angular angular2-forms

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

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

有一个 form-input-component 并捕获一些属性并将其传递给内部的标记

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

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

显然在我的ts中

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

然后在 View 中我有一些东西

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

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

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

我如何传递来自 <form-input> 的任何其他内容?到我的<input>在 View 中?

最佳答案

对于懒惰的人:

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 的原因。

关于javascript - Angular 2 : passing ALL the attributes to the child component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43785547/

相关文章:

Javascript:使用 Promise 时需要帮助防止代码重复

javascript - ExtJS:有没有办法处理内存管理

html - 如何在 Angular 2 中将输入值转换为大写(传递给 ngControl 的值)

angular - 在我的 Angular 项目上升级到 ngrx v8 后如何修复 "NullInjectorError: No provider for InjectionToken @ngrx/router-store Configuration!"?

angular - 测试 - stub 服务方法未定义

Angular2 显示所有表单组验证错误

Angular 2 FormGroup动态添加验证器

javascript - 在 .js 文件中调用 URL 参数

javascript - 单击时将表格单元格从跨度更改为输入

google-maps - Angular2 - 如何设置 google.maps.OverlayView? (将 JS 原型(prototype)翻译成 Typescript)