[英]Check if component have attribute selector in angular2
我想检查Angular2中组件是否具有属性。 这是我的组件:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'field-group, field-group[half]',
template: `
<div class="field-group">
<label *ngIf="label != ''">{{label}}</label>
<ng-content></ng-content>
<span class="validation" *ngIf="errorObject != ''"></span>
</div>
`
})
export class FieldGroupComponent implements OnInit {
@Input() label: string = '';
@Input() errorObject: any;
constructor() { }
ngOnInit() { }
}
对于选择器,我添加了[half]
。 现在我如何检查该组件在使用时在代码中是否具有该选择器? 我在哪里可以检查是否存在? 如何?
谢谢。
将其转换为输入:
selector: '[field-group]'
接着
@Input('field-group') fieldGroup: string;
实例化为:
<div [field-group]='half'>...</div>
要么 ...
然后在您的代码中(例如ngInit
):
if(fieldGroup === 'half'){...
推荐的解决方案是使用@Input
读取属性的值,但不能保证属性的存在与空属性。 请参阅演示: https : //plnkr.co/edit/wYuiRS8gYcyiYZt79yko?p=preview
不建议使用但适合的解决方案是使用ElementRef
来获取组件元素的ElementRef
以检查属性的存在。
import { Component, OnInit, Input, ElementRef } from '@angular/core';
@Component({
selector: 'field-group, field-group[half]',
template: `
<div class="field-group">
<label *ngIf="label != ''">{{label}}</label>
<ng-content></ng-content>
<span class="validation" *ngIf="errorObject != ''"></span>
</div>
`
})
export class FieldGroupComponent implements OnInit {
label: string = '';
errorObject: any;
constructor(private elementRef: ElementRef) { }
ngOnInit() {
console.log(this.elementRef.nativeElement.getAttribute('half'));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.