甚至不知道解释这个问题的正确术语
所以,想象一下这个场景......
有一个 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/