【发布时间】:2016-06-06 02:53:44
【问题描述】:
我的问题是我试图在 Angular 2 中创建一个 Attribute 指令,它允许我从一个自定义属性定义多个默认 html 属性。我正在尝试专门在输入元素上使用它。问题出现在我似乎无法获得对属性附加到的元素的引用我知道使用视图查询可以获取对子元素(作为视图一部分的元素)的引用,但是因为它是一个属性指令它没有视图,我需要的元素是指令所在的元素。这是我到目前为止的代码。请注意,这一切都在 es5 中,我无法使用 typescript 或任何其他编译器。
父组件和引导
$(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 的某个地方,但我不知道如何将它正确地注入到我的脚本中。
【问题讨论】:
-
this.viewChild有什么用吗? -
如果您指的是在普通子查询中使用的 ng.core.ViewChild,它没有帮助,因为它是一个属性指令,因此没有视图或子项。
-
"<input type='range' [multiAttr]='input' #input />" -
@EricMartinez 不,这会给我一个文字字符串“input”,即使我让它评估它所做的只是在测试组件上查找一个名为 input 的变量
-
不,这不会给你一个文字“输入”字符串。这会给你元素本身。
标签: javascript angular