2016-12-23 20 views
2

通過結構指令,我將如何獲得指令所在的(本地)元素的持有? 與正常的指令後,ElementRef有它的nativeElement指向它 - 比如:結構指令 - 找到它放置的元素

<input type="text" example> 

@Directive({ 
    selector: '[example]' 
}) 
export class ExampleDirective {  

    constructor(private el: ElementRef) {} 

    ngAfterViewInit() { 
    console.log(this.el.nativeElement); // the input 
    } 
} 

但隨着結構性指令,它指向模板評論 - 如。

<input type="text" *example> 

@Directive({ 
    selector: '[example]' 
}) 
export class ExampleDirective { 

    constructor(
    private el: ElementRef, 
    private view: ViewContainerRef, 
    private template: TemplateRef<any> 
) {} 

    ngAfterViewInit() { 
    this.view.createEmbeddedView(this.template); 

    console.log(this.el.nativeElement); // template bindings comment 
    // how to find the input itself? 
    } 
} 

我使用ViewContainerRef,TemplateRef,@ContentChild,@ViewChild的各種組合嘗試 - 只是似乎沒有能夠找到輸入元素本身......

+0

你試圖解決的實際問題是什麼? –

回答

3

所有結構指令是添加到<template>元素。 Angular從不會向DOM添加<template>元素。因此無法獲取結構指令添加到的元素。

如果您使用*

<div *ngIf="..."></div> 

角創建

<template [ngIf]="..."> 
    <div></div> 
</template> 

而且因爲沒有添加<template>,沒有得到它的方式,因爲<div>是不是該元素的語法速記結構指令添加到您也無法使用指令引用獲取此元素。

+0

感謝甘特 - 我開始認爲這是可悲的情況。我知道角度如何將結構指令擴展到模板中,我只是希望仍然有一些參考可用於所使用的元素 - 並不是這樣看的。似乎是一個超現場。 我可以看到輸入元素(在TemplateRef的nextSibling下) - 但沒有一個很好的gettable方法。 –

+0

如果你想詳細說明一下實際的問題,你試圖解決一些替代方法可能會被揭示。 –

-1

基礎上Structural Directives Documentation(不知道它的工作原理,但也許可以幫助你):

<input type="text" *example> 


@Directive({ 
    selector: '[example]' 
}) 
export class ExampleDirective { 

    constructor(private viewContainer: ViewContainerRef) { } 

    @Input() set example() { 
    console.log(this.viewContainer.element.nativeElement.value); 
    } 
} 
+0

謝謝@lenny,但我確實嘗試過這種方式 - 希望它可以工作,但它不會 - 你會得到一個未定義的(在你的例子中)this.input - 所以沒有nativeElement可用。 –

+0

@CalvJ對不起,我以前的答案是錯的。我**更新**,不知道它是否有效,但也許可以幫助你。 – lenny

+0

:-)再次感謝 - 但(this.viewContainer.element.nativeElement)仍然只是抓住你的評論!我想也許甘特是正確的,並沒有直接的辦法來抓住它。 –

0

這不是很漂亮,但爲我工作:

this.viewContainer.get(0).rootNodes[0] 

我用它當實施版本*ngIf指令,但動畫:animatedIf