Angular dart-带有ngModel

时间:2019-12-28 15:01:15

标签: angular angular-dart

我正在尝试创建一个自定义输入文本组件,但是我不知道如何使其与ngModel指令一起使用。

我尝试复制material angular_component input,但不了解inputText属性实际上是如何与ngModel值链接的,以及DefaultValueAccessor指令的用途是什么

这是我期望使用组件的方式:

<my-input-component [(ngModel)]="someProp"><my-input-component>

(其中my-input-component的内容只是带有标签的普通<input type="text">字段)

任何想法或示例/文档的链接将不胜感激。

1 个答案:

答案 0 :(得分:0)

在调试angular_components代码之后,我自己找到了答案。您必须实现ControlValueAccessor并注册ngValueAccessor提供程序(实际上是缺少的部分)。

这是我的解决方法:

// my_custom_component.dart
@Component(
  selector: 'my-custom-component',
  templateUrl: '<div class="input-wrapper">{{value}}</div>',
  providers: [
    ExistingProvider.forToken(ngValueAccessor, MyCustomComponent),
  ],
)
class MyCustomComponent implements ControlValueAccessor<String> {
  String value;
  // ...could define a setter that call `_changeController.add(value)`

  final _changeController = StreamController<String>();

  @Output()
  Stream<String> get onChange => _changeController.stream;

  @override
  void writeValue(String newVal) {
    value = newVal ?? '';
  }

  @override
  void registerOnChange(callback) {
    onChange.listen((value) => callback(value));
  }

  // optionally you can implement the rest interface methods
  @override
  void registerOnTouched(TouchFunction callback) {}

  @override
  void onDisabledChanged(bool state) {}
}
// app_component.dart
@Component(
  selector: 'app-component',
  templateUrl: '''
    <my-custom-component [(ngModel)]="data"></my-custom-component>
  ''',
  directives: [
    NgModel,
    MyCustomComponent,
  ],
)
class AppComponent {
  String data;
}

注意:angular_component使用指令,但主要思想是相同的。

相关问题