0

I wanna check if component has an attribute or not in Angular2. here is my component:

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() { }

}

For the selector I added [half]. now how can I check this component have this selector in code when I used? where can I check this exist or not? and how?

Thanks.

2 Answers 2

3

The recommended solution would be to read the attribute's value using @Input but does not guarantee attribute's existence vs empty attribute. Refer the demo: https://plnkr.co/edit/wYuiRS8gYcyiYZt79yko?p=preview

Non-recommended but suitable solution for you is to get the hold of the component element to check the attribute's existence using 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'));
    }

}
Sign up to request clarification or add additional context in comments.

Comments

2

Convert it to input:

selector: '[field-group]'

and then

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

Instantiation becomes:

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

or ...

then in your code (for example in ngInit):

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.