2017-01-22 4 views
0

コンポーネントにアングル2の属性があるかどうかを確認します。ここに私のコンポーネントです:コンポーネントにangle2のアトリビュートセレクタがあるかどうかを確認します。

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]を追加しました。今私が使用したときに、このコンポーネントにこのセレクタがあることを確認するにはどうすればいいですか?これが存在するかどうかはどこで確認できますか?そしてどうやって?

ありがとうございました。

答えて

1

入力に変換します

selector: '[field-group]' 

、その後

@Input('field-group') fieldGroup: string; 

インスタンスは次のようになります。

<div [field-group]='half'>...</div> 

または ...

を、あなたのコード内で(のためにエキスパngInitでmple):

if(fieldGroup === 'half'){... 
1

推奨される解決策は@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')); 
    } 

} 
関連する問題