2017-07-31 17 views
1

我正在嘗試將一些JavaScript聚合物元素移植到AngularDart。如何在AngularDart中訪問DOM?

我需要能夠做相當於this.$.contentContainer.getBoundingClientRect();(對於那些不熟悉聚合物,基本上是component.getElementById("contentContainer").getBoundingClientRect())。

我還需要能夠訪問主機元素來執行諸如window.getComputedStyle(this).direction其中this是主機元素。

這樣的事情通常會在AngularDart中完成嗎?

回答

3

你可以注入的對象調用ElementRef

import 'dart:html'; 

class Comp { 
    final ElementRef _elementRef; 

    Comp(this._elementRef) { 
    final element = _elementRef.nativeElement as Element; 
    element.getComputedStyle(); // ... 
    } 
} 

在AngularDart 4.x中,我們將允許你直接注入Element

2

另外,您可以使用@ViewChild()

@Component(
    selector: 'my-component', 
    template: ''' 
<div #contentContainer></div> 
''' 
) 
class MyComponent implements AfterViewInit { 
    @ViewChild('contentContainer') ElementRef cc; 

    ngAfterViewInit() { 
    (cc.nativeElement as HtmlElement).... 
    } 
} 

參見angular 2/typescript : get hold of an element in the template(適用與如右圖類型和可選參數{}小的改動DART)

+0

這是否得到一個特定元素的引用允許你獲取主機元素嗎? – crossboy007

+0

如果您想要主機元素,請使用@matanlurey顯示的方法 –