2017-07-10 41 views
0

我正在编写一些代码,用dart更新div的位置。ElementRef没有样式的实例

所以,我想到了一个类似于鼠标放在div上的东西,开始更新元素的位置。

的HTML将如下:

<div (mousedown)="mouseDownFunction($event)"></div> 
<div #selection></div> 

与镖看起来像:

@ViewChild("selection") 
DivElement selectionDiv; 

mouseDownFunction(mouse){ 
    selectionDiv.style.left = "${mouse.position.left}px"; 
} 

,当这种情况发生,它试图调用style上selectionDiv,但是他说,ElementRef没有样式的实例。

enter image description here

回答

3

这是预期的功能。 selectionDiv不是DivElement,而是ElementRef。要获取dart:html元素,请使用getter selectionDiv.nativeElement。 希望这有助于。

+0

所以我应该更新我所有的ViewChild属性为ElementRef,然后根据需要进行调整?我不是说这是错误的,但你认为有没有办法指向目标? – Fallenreaper

+0

是的,除非元素是一个Angular组件,否则它将是一个ElementRef。 –

+0

这是否允许设置本地元素的属性?当我尝试进行调整时,我没有看到任何与nativeElement风格相关的任何调整 – Fallenreaper

2

由于Tobe O在他的answer中提出的问题是selectionDivElementRef而不是DivElement

但我想补充一点,启用checked mode可以帮助您在将来尽早发现这种错误。默认情况下Dartium不执行类型检查。如果您想从类型注释中受益,则启动Dartium时需要specify the --checked VM flag

在Linux上,你可以做这样的事情,使检查模式:

DART_FLAGS='--checked' path/to/dartium 

现在您的代码应产生以下错误信息:具备

ORIGINAL EXCEPTION: type 'ElementRef' is not a subtype of type 
'DivElement' of 'value' where 
    ElementRef is from package:angular2/src/core/linker/element_ref.dart 
    DivElement is from dart:html 

堆栈跟踪上面的错误信息可以告诉你哪个变量导致了错误。

ORIGINAL STACKTRACE: 
#0  MyComponent.selectionDiv= (package:my_package/my_component.dart:15:14) 
相关问题