我有两个组件:
@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
的值