[英]Angular2: passing ALL the attributes to the child component
Don't even know the proper terminology to explain this problem甚至不知道解释这个问题的正确术语
so, imagine this scenario...所以,想象一下这个场景......
There is a form-input-component and capturing some attributes and passing it down to the markup inside有一个表单输入组件并捕获一些属性并将其传递给内部的标记
<form-input placeholder="Enter your name" label="First name" [(ngModel)]="name" ngDefaultControl></form-input>
So, this is the markup, hope is pretty self explanatory...所以,这是标记,希望是不言自明的......
obviously in the ts I have显然在我拥有的 ts 中
@Input() label: string = '';
@Input() placeholder: string = '';
and then in the view I have something down these lines然后在视图中我有一些东西
<div class="form-group">
<label>{{label}}
<input type="text" [placeholder]="placeholder" [(ngModel)] = "ngModel">
</div>
Now, all works fine so far...现在,到目前为止一切正常......
but let's say I want to add the validation rules around it... or add other attributes that I don't capture via @Input()
但是假设我想围绕它添加验证规则……或者添加我没有通过
@Input()
捕获的其他属性
How can I pass down anything else that comes down from <form-input>
to my <input>
in the view?如何将来自
<form-input>
其他任何内容传递到视图中的<input>
?
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.如果嵌套多个传递属性的组件,
ngAfterViewInit
将不起作用,因为ngAfterViewInit
将在外部元素之前为内部元素调用。 Ie 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.这就是我在这里使用
ngOnInit
的原因。
You could iterate on the DOM attributes of your component :您可以迭代组件的 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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.