8

私はselectorにアクセスして、@Componentデコレータに渡す方法を理解しようとしています。例Angular 2コンポーネント内から `selector 'にアクセスする

@Component({ 
    selector: 'my-component' 
}) 
class MyComponent { 
    constructor() { 
    // I was hoping for something like the following but it doesn't exist 
    this.component.selector // my-component 
    } 
} 

については

最終的に、私は確実に彼らの選択によって、私の角度の要素を見つけるために、セレンクエリを使用できるように自動的に属性data-tag-name="{this.component.selector}"を追加するディレクティブを作成するためにこれを使用したいと思います。あなたがAOT compilerを実行したときに注釈が取り除かます

重要な注意:私は分度器

答えて

12

使用ElementRef

import { Component, ElementRef } from '@angular/core' 

@Component({ 
    selector: 'my-component' 
}) 
export class MyComponent { 
    constructor(elem: ElementRef) { 
    const tagName = elem.nativeElement.tagName.toLowerCase(); 
    } 
} 
+0

これはおそらくこれを行う唯一の方法です。古い(今は壊れた)方法は、注入を追加する必要がなく、インスタンスを必要とせずにアクセスできるため、終了時に使用します重複を最小限に抑えるためにテストを終了します。 –

7

古いを使用していない

はあなたのコンポーネントに関連付けられたメタデータを取得する必要がありhttps://stackoverflow.com/a/42579760/227299

を参照してください。テンプレートをあらかじめコンパイルしている場合、このソリューションを無効にする

@Component({ 
    selector: 'my-component' 
}) 
class MyComponent { 
    constructor() { 
    // Access `MyComponent` without relying on its name 
    var annotations = Reflect.getMetadata('annotations', this.constructor); 
    var componentMetadata = annotations.find(annotation => { 
     return (annotation instanceof ComponentMetadata); 
    }); 
    var selector = componentMetadata.selector // my-component 
    } 
} 
+0

これは有望に見える、我々はそれは何も語っていない場合は、 'は、' MyComponent'のメタデータを探すことになっていますことを知ることができるReflect.getMetadata'する方法?私は現在、 'Reflect.getMetadata( 'annotations');'エラーを返す 'Reflect.getMetadata( 'annotations') VM61 angular2.sfx.dev.js:2652未知のTypeError(...)getMetadata @ Reflect.getMetadata( 'annotations'、this、 'annotations') '2つの余分なパラメータが必要なようです。 –

+1

' this.constructor'を2番目の引数として渡して答えを修正しました。 –

+2

この回答は、該当する角度2のバージョンで修飾してください。リリース2.3.0では、これは古くなっているようです – Neoheurist

関連する問題