在 Angular Dart 组件中填充派生字段 [英] Populating derived fields in an Angular Dart component

查看:17
本文介绍了在 Angular Dart 组件中填充派生字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个采用单一属性的组件.我想使用从该属性派生的值填充组件中的字段.我遇到的问题是,当构造函数中的代码运行时,没有发生与属性的绑定.那么,如何设置派生字段的值?

I have a component that takes a single attribute. I want to populate a field in the component with a value that is derived from this attribute. I am running into the problem that the binding with the attribute has not happened when the code inside the constructor runs. How, then, do I set the value of the derived field?

这是一些代码:

import 'package:angular/angular.dart';

@NgComponent(
    selector: 'tokens',
    templateUrl: './component.html',
    cssUrl: './component.css',
    publishAs: 'ctrl',
    map: const {
      'text' : '@text'
    }
)
class TokensComponent {
  String text;

  // Derived field.
  List<Token> tokens = new List<Token>();

  TokensComponent() {
    print('inside constructor, text = $text'); // $text is null.
  }

}

class Token {
  String char;
  bool important;
  Token(this.char, this.important);
}

推荐答案

派生字段的当前最佳实践是按需计算它们并缓存结果.通过等待,当未使用派生字段时,应用程序可能能够避免不必要的工作.

The current best practice for derived fields is to calculate them on-demand and cache the results. By waiting, the app may be able to avoid unneeded work when the derived field isn't being used.

例如您的示例组件如下所示:

e.g. your example component would look like:

import 'package:angular/angular.dart';

@NgComponent(
    selector: 'tokens',
    templateUrl: './component.html',
    cssUrl: './component.css',
    publishAs: 'ctrl',
    map: const {
      'text' : '@text'
    }
)
class TokensComponent {
  Map<bool, List<Token>> _tokensCache = new Map<bool, List<Token>>();

  String _text;
  get text => _text;
  set text(t) {
    _text = t;
    _tokensCache.clear();  // invalidate the cache any time text changes.
  }

  // Derived field.
  List<Token> get tokens =>
    text == null ? [] : _tokensCache.putIfAbsent(true,
        () => text.split('').map((char) =>  new Token(char, false)));

}

现在,令牌总是最新的,如果没有任何东西要求令牌,组件就不会计算该字段.

Now, tokens is always up-to-date, and if nothing ever asks for tokens, the component doesn't compute that field.

在这个例子中,缓存是必需的.由于 Angular 的脏检查使用 identical 来检查更改,如果组件没有更改,我们的组件必须返回相同的标记列表.

In this example, the cache is required. Since Angular's dirty checking uses identical to check for changes, our component must return an identical tokens list if the component has not changed.

这篇关于在 Angular Dart 组件中填充派生字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆