Populating derived fields in an Angular Dart component

好久不见. 提交于 2019-12-01 20:26:18

One possible solution is to ave the component implement NgAttachAware and define the attach() method. The value of the derived field can then be set inside attach(). I have no idea if there is a more idiomatic way to do this, but using attach() seems to work.

Here is the code:

import 'package:angular/angular.dart';

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

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

  TokensComponent() {
    print('inside constructor, text = $text');
  }

  void attach() {
    print('inside attach(), text = $text'); // $text is no longer null.
    text.split('').forEach((char) => tokens.add(new Token(char, false)));
  }
}

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!