angular 2 ElementRef in es5

3
我的问题是,我正在尝试在Angular 2中创建一个属性指令,该指令允许我从一个自定义属性中定义多个默认HTML属性。我尝试将其专门用于input元素。问题出现在我似乎无法获取附加到属性的元素的引用。我知道使用视图查询可以获取对子元素(作为视图的一部分的元素)的引用,但由于它是属性指令,它没有视图,而我需要的元素是指令所在的元素。这是我目前拥有的代码。请注意,它全部都是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 有用吗? - dandavis
如果你正在引用ng.core.ViewChild,它在普通子查询中使用是没有帮助的,因为它是一个属性指令,因此没有视图或子元素。 - Binvention
"<input type='range' [multiAttr]='input' #input />" - Eric Martinez
@EricMartinez 不,那会给我一个字面上的字符串“input”,即使我让它评估所有内容,它也只会在测试组件中查找名为input的变量。 - Binvention
不,那不会给你一个字面上的“输入”字符串。那会给你元素本身。 - Eric Martinez
这是因为 #input 吗?顺便说一句,你确实需要评估它,否则它只会返回 "input",因为它不会在没有 [] 的情况下将字符串作为代码进行评估。 - Binvention
1个回答

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元素。

如何将 ElementRef 导入到您的模块中?通过 imports 吗? - Saeed Neamati

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接