【问题标题】:AngularDart: cannot cast to a material componentAngularDart:无法转换为材料组件
【发布时间】:2017-09-08 19:19:24
【问题描述】:

我有一个 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。

【问题讨论】:

    标签: dart angular-material angular-dart


    【解决方案1】:

    无法从以这种方式查询的元素中获取组件实例。

    你可以使用@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中没有使用。

    【讨论】:

    • 就像一个魅力,刚刚尝试过。我查了一些关于生命周期钩子的信息。你为什么专门实现 AfterViewInit 而不是,例如,AfterViewChecked? AfterViewInit 执行时渲染完成了吗?顺便说一句,tnx Günter。
    • ngAfterViewInit 在视图和内容初始化后只调用一次。 ngAfter*Checked 可以多次调用。 angular.io/guide/lifecycle-hooks
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2017-09-19
    • 2020-04-11
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    相关资源
    最近更新 更多