AngularDart:无法强制转换为材质组件

时间:2017-09-08 19:19:25

标签: dart angular-material angular-dart

我有一个dart应用,其中包含一个带有材质复选框的模板,我无法在我的组件中使用。这是一个演示问题的简单模板(two_boxes.html):

<!--
Simple HTML to test checkboxes
-->

<input type="checkbox" id="cb0">
<label>Standard Checkbox</label>

<material-checkbox label="Material Checkbox" id="cb1">
</material-checkbox>

<button (click)="doTest()">Test</button>

和我尝试使用复选框的相应组件(two_boxes.dart)。我可以按预期使用强制转换中的标准复选框,但无法找到对材质复选框执行相同操作的方法:

// Component for testing

import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';

import 'dart:html';

@Component(
    selector: 'two-boxes',
    templateUrl: 'two_boxes.html',
    directives: const [MaterialCheckboxComponent],
    pipes: const [
      COMMON_PIPES
    ])
class TwoBoxes {

  // Get the the two checkboxes and see if they are checked
  void doTest() {
    var checkbox_standard = querySelector("#cb0");
    print(checkbox_standard.runtimeType.toString()); // InputElement
    print((checkbox_standard as CheckboxInputElement).checked); // Succeeds

    var checkbox_material = querySelector("#cb1");
    print(checkbox_material.runtimeType.toString()); // HtmlElement
    print((checkbox_material as MaterialCheckboxComponent).checked); // Error!
  }
}

当我在Dartium中使用“pub serve”(无错误)运行应用程序后,最后一条语句失败:

VM54:1 EXCEPTION: type 'HtmlElementImpl' is not a subtype of type
MaterialCheckboxComponent' in type cast where HtmlElementImpl is 
from dart:html MaterialCheckboxComponent is from   
package:angular_components/src/components/
material_checkbox/material_checkbox.dart

显然,这种投射方式不起作用。我搜索了几个小时如何解决这个错误并找到正确的方法来做到这一点,但显然在错误的地方。我在这里错过了什么?我使用的是Dart VM版本1.24.2。

1 个答案:

答案 0 :(得分:0)

无法通过这种方式查询元素中的组件实例。

您可以使用@ViewChild()

class TwoBoxes implements AfterViewInit {

  @ViewChild(MaterialCheckboxComponent) MaterialCheckboxComponent cb;

  ngAfterViewInit() {
    print(cb.checked);
  }

如果你有一个特定的一个,你可以使用一个模板变量

<material-checkbox #foo label="Material Checkbox">

@ViewChild('foo') MaterialCheckboxComponent cb;

您可以在此TypeScript答案angular 2 / typescript : get hold of an element in the template

中找到有关此主题的更多信息

语法略有不同(右侧的类型注释和可选的{}参数周围的read,Dart中未使用这些注释。

相关问题