【问题标题】:AngularDart - how to get an element from its id?AngularDart - 如何从它的 id 中获取一个元素?
【发布时间】:2019-11-21 16:56:27
【问题描述】:

(使用 AngularDart 的第一个小时...)

问题在标题中。我已经包括:

import 'package:html/src/query_selector.dart';

我的功能是:

void clickRadio() {
  var ele=querySelector(node,'#idjoe1');
}

节点有什么用?

谢谢

史蒂夫

【问题讨论】:

    标签: angular-dart


    【解决方案1】:

    dart 带有 dart:html 包和一个不错的查询选择器

    import 'dart:html';
    
    var ele = querySelector('#idjoe1');
    
    <div id="idjoe1"></div>
    

    但是使用 angular2,您可以在组件中使用 ViewChild 注释 https://webdev.dartlang.org/angular/api/angular2.core/ViewChild-class

    编辑: 如果你想使用其他 Angular2 组件,你也需要这个语法

    @ViewChild('idjoe1')
    MaterialRadioComponent radioComponent;
    
    @ViewChild('idjoe2')
    ElementRef ref;
    HtmlElement get element => ref.nativeElement;
    
    <material-radio #idjoe1></div>
    <div #idjoe2></div>
    

    【讨论】:

    • 谢谢。我在聚合物中使用了 dart.html,但是当我在这里尝试时,我定义了类型: MaterialRadioComponent ele=querySelector('#idjoe1') ,我认为是 querySelector 有问题。因此,在 Webstorm 中,如果我在调试中使用 Element ele=...,它会将 ele 显示为类型“material-radio”(我不能将其写为代码中的类型)。我应该将类型定义为什么?
    • 我更新了我的答案。如果您还没有,您应该遵循本教程。 webdev.dartlang.org/angular/tutorial
    【解决方案2】:

    在最近的版本中,您可以在构造函数中注入 ElementHtmlElement(我认为它会为您提供主机元素):

    HtmlElement _host;
    MyComponent(this._host);
    

    或者您可以将@ViewChildElementHtmlElement 一起使用:

    @ViewChild('foo')
    HtmlElement _foo;
    
    ...
    
    <div #foo>
    

    【讨论】:

      猜你喜欢
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多