如何从子组件读取值

  • 本文关键字:读取 组件 angular-dart
  • 更新时间 :
  • 英文 :


我有两个组件:

@Component(
selector: 'parent',
directives: [
ChildComponent,
],
templateUrl: 'parent.html',
)
class ParentComponent {
Result parentResult;
}

@Component(
selector: 'child',
templateUrl: 'child.html',
)
class ChildComponent {
@Output()
Result childResult;
}

childResult改变时,我希望parentResult改变为新的值。我该怎么做呢?我试着这样做:<child [parentResult]="childResult">...</child>parent.html文件中,但我尝试的组合都不起作用。我还试过让子构造函数采用ParentComponent,但注入系统不喜欢这样。

@Output()确实是你所需要的。但是它必须是Stream,这样你的父元素才能监听它。

@Component(
selector: 'child',
templateUrl: 'child.html',
)
class ChildComponent implements OnDestroy {
final _resultController = StreamController<Result>();
@Input()
Result result;
@Output()
Stream<Result> get onResultChange => _resultController.stream;
void changeResult(Result newResult) {
result = newResult;
onResultChange.add(newResult);
}
void ngOnDestroy() {
// close stream controller to avoid memory leak
_resultController.close();
}
}

然后在父组件中绑定Output

<child (onResultChange)="result = $event"></child>

PS:(xxx)=""语法用于绑定组件的@Output[xxx]=""用于设置@Input的值