Reputation: 1077
My problem is that I'm trying to make an Attribute directive in angular 2 that allows me to define multiple default html attributes from one custom attribute. I'm trying to use it specifically on the input element. the problem arises in that i can't seem to get a reference to the element the attribute is attached to i know that using view query you can get references to child elements (elements that are part of the view) but because its an attribute directive it doesn't have a view and the element i am needing is the element within which the directive rests. here's the code i have so far. please note that it is all in es5 i am unable to use typescript or any other compiler.
parent component and bootstrap
$(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={}));
multi attribute directive
(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>
I think the answer lies somewhere in ng.core.ElementRef but I can't figure out how to properly inject it into my script.
Upvotes: 3
Views: 957
Reputation: 202216
I think that you can inject the ElementRef
in your directive:
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(){
(...)
}
});
The eltRef.nativeElement
returns the DOM element corresponding to your input.
Upvotes: 3