[英]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.