【问题标题】:Angular dart - custom input component with ngModelAngular dart - 带有 ngModel 的自定义输入组件
【发布时间】:2019-12-28 15:01:15
【问题描述】:

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

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

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

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

my-input-component 的内容只是一个带有标签的普通 &lt;input type="text"&gt; 字段)

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

【问题讨论】:

  • 我不这么认为,因为你不能让 Input() 和 Output() 同名。

标签: angular angular-dart


【解决方案1】:

调试了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 使用指令但主要思想是一样的。

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 2016-02-06
    • 2018-11-10
    • 2020-07-02
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多