我想从子组件向应用程序组件发出一个值。组件结构如下:
index.html:
<app-root></app-root>
app.component.html:
<router-outlet></router-outlet>
app.component.ts:
@Component({
selector: 'app-root',
...
})
export class AppComponent implements OnInit {
change = false;
...
getStatus(value: boolean): void {
this.change = value;
}
...
}
child.component.ts(通过路由器出口呈现,例如从类似/child的URL(:
@Component({
selector: 'app-child',
...
})
export class ChildComponent implements OnInit {
@Output() doStuff: EventEmitter<boolean> = new EventEmitter<boolean>();
...
emitStuff(): void {
this.doStuff.emit(true);
}
}
child.component.html:
<a (click)="emitStuff()">Click</a>
现在,我应该将(doStuff)="getStatus()
绑定连接到哪里?
通常在<app-child (doStuff)="getStatus()">
中,但这不可用,例如在编写<app-child></app-child>
选择器的静态app.component.html中。我就是不明白,对不起;(
在父组件中,您可以使用检索当前组件的实例
<router-outlet (activate)="onActivate($event)" (deactivate)="onDeactivate()"></router-outlet>
然后订阅孩子的EventEmitter
,它只不过是一个Observable
:
onActivate(component) {
if(component instanceof ChildComponent) {
this.doStuffSubscription = component.doStuff.subscribe(x => ...);
}
}
onDeactivate() {
if(this.doStuffSubscription)
this.doStuffSubscription.unsubscribe();
}