2014-01-12 40 views
3

我有一个组件只接受一个属性。我想使用从此属性派生的值填充组件中的字段。当运行构造函数中的代码时,我遇到了与属性的绑定没有发生的问题。那么,我如何设置派生字段的值?在角度飞镖组件中填充派生字段

下面是一些代码:

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); 
} 

回答

3

一种可能的解决方案是AVE组件实现NgAttachAware并定义attach()方法。派生字段的值可以在attach()内设置。我不知道是否有更习惯的方式来做到这一点,但使用attach()似乎工作。

下面是代码:

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); 
} 
3

目前的最佳做法导出字段是计算它们点播和高速缓存的结果。通过等待,应用程序可能能够避免在派生字段未被使用时不需要的工作。

例如你的榜样组件看起来像:

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))); 

} 

现在,令牌始终是最新的,如果从来都没有请求令牌,该组件不计算该字段。

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