我有一个采用单个属性的组件。我想用从此属性派生的值填充组件中的字段。我遇到的问题是,当构造函数内的代码运行时,与属性的绑定尚未发生。那么,如何设置派生字段的值呢?
这是一些代码:
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);
}
一种可能的解决方案是使用组件实现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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)