简体   繁体   English

检查组件是否在angular2中具有属性选择器

[英]Check if component have attribute selector in angular2

I wanna check if component has an attribute or not in Angular2. 我想检查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] . 对于选择器,我添加了[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. 谢谢。

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 ): 然后在您的代码中(例如ngInit ):

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

The recommended solution would be to read the attribute's value using @Input but does not guarantee attribute's existence vs empty attribute. 推荐的解决方案是使用@Input读取属性的值,但不能保证属性的存在与空属性。 Refer the demo: https://plnkr.co/edit/wYuiRS8gYcyiYZt79yko?p=preview 请参阅演示: 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 . 不建议使用但适合的解决方案是使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM