我想在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]
。现在,当我使用时,如何在代码中检查此组件是否有此选择器?我在哪里可以查看是否存在?怎么样?
感谢。
答案 0 :(得分:2)
将其转换为输入:
selector: '[field-group]'
然后
@Input('field-group') fieldGroup: string;
实例化变为:
<div [field-group]='half'>...</div>
或 ...
然后在您的代码中(例如在ngInit
中):
if(fieldGroup === 'half'){...
答案 1 :(得分:2)
建议的解决方案是使用@Input
读取属性的值,但不保证属性的存在与空属性。请参阅演示:https://plnkr.co/edit/wYuiRS8gYcyiYZt79yko?p=preview
非推荐但适合您的解决方案是获取组件元素以使用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'));
}
}