ElementRef 没有样式实例

ElementRef has no instance of style

我正在编写一些代码,这些代码将用飞镖更新 div 的位置。

所以,我想到的是,将鼠标放在 div 上,开始更新元素的位置。

html将如下:

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

飞镖看起来像:

@ViewChild("selection")
DivElement selectionDiv;

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

发生这种情况时,它会尝试在 selectionDiv 上调用 style,但表示 ElementRef 没有样式实例。

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

正如 Tobe O 在他的 中所建议的那样,问题是 selectionDivElementRef 而不是 DivElement

但我想在启动 Dartium 时添加启用 checked mode could help you catch this kind of error early in the future. By default Dartium performs no type checking. If you want to benefit from your type annotations, you need to 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)