2016-02-24 98 views
3

我的問題是我試圖在角度2中創建一個Attribute指令,它允許我從一個自定義屬性中定義多個默認的html屬性。我試圖在輸入元素上專門使用它。問題出現在我似乎無法獲得該屬性所附的元素的引用我知道使用視圖查詢可以獲取對子元素(視圖的一部分的元素)的引用,但因爲它的屬性指令它沒有視圖,我需要的元素是指令所在的元素。這是我到目前爲止的代碼。請注意,它全部在es5中,我無法使用打字機或任何其他編譯器。angular 2 ElementRef in es5

父組件和引導

$(document).ready(function(){ 
    ng.platform.browser.bootstrap(app.testing); 
}); 
(function(app){ 
    app.testing=ng.core.Component({ 
     selector:"testing", 
     //this is the element i need a reference to 
     //i would like to assign the min max and step properties using one attribute 
     template:"<input type='range' multiAttr='hello world' #input />", 
     directives:[app.multiAttr], 
    }).Class({ 
     constructor:[function(){}], 
    }); 
})(window.app||(window.app={})); 

多屬性指令

(function(app){ 
    app.multiAttr=ng.core.Directive({ 
     selector:"[multiAttr]", 
     inputs:["multiAttr"], 
     queries:{"input":new ng.core.ElementRef()}, 
    }).Class({ 
     constructor:[function(){ 
     }], 
     ngAfterViewInit:function(){ 
      //here is where i need my element reference 
      console.log(this.input); 
      console.log(this.multiAttr); 
     } 
    }); 
})(window.app||(window.app={})); 

HTML

<!DOCTYPE html> 
<html> 
<head> 
</head> 
<body> 
<testing></testing> 
<script src='../jquery.min.js'></script> 
<script src='../Rx.umd.min.js'></script> 
<script src='../angular2-polyfills.min.js'></script> 
<script src='../angular2-all.umd.js'></script> 
<script src='multiAttr.js'></script> 
<script src='testing.js'></script> 
</body> 
</html> 

我想答案就在於某處ng.core.ElementRef但我不能弄清楚如何正確地將它注入到我的腳本中。

+0

是'this.viewChild'什麼都沒有用? – dandavis

+0

如果您指的是在正常子查詢中使用的ng.core.ViewChild,它不會幫助,因爲它的屬性指令並沒有視圖或子視圖。 – Binvention

+0

''「' –

回答

3

我認爲你可以在你的指令注入ElementRef:相當於你輸入

var multiAttrDirective = ng.core.Directive({ 
    selector:"[multiAttr]", 
    inputs:["multiAttr"] 
}).Class({ 
    constructor:[ng.core.ElementRef, function(eltRef){ 
    console.log(eltRef); 
    console.log(eltRef.nativeElement); 
    }], 
    ngAfterViewInit:function(){ 
    (...) 
    } 
}); 

eltRef.nativeElement返回的DOM元素。

+0

如何將ElementRef導入你的模塊?通過'進口'? –