我有这个 ruote 配置:
const routes: Routes = [
{ path: 'score', component: ScoreComponent }
];
加载组件分数时,我想更改父组件中变量的值。
变量标题位于父组件模板中:
<div class="wrapper">
<app-header></app-header>
<app-menu [variablesForMenu]='variablesForMenu'></app-menu>
<div class="content-wrapper">
<section class="content-header">
<h1>
{{title}}
</h1>
</section>
<section class="content">
<router-outlet></router-outlet>
</section>
</div>
</div>
我该怎么办?
我想使用事件发射器,但我不知道如何
三种方法:
- 使用 BehaviorSubject,在父级中订阅它,并在 init 上在子级中调用
next
。
SomeService.service.ts
em: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
Parent.component.ts
variableToChange: any;
sub: Subscription;
constructor(someService: SomeService){}
ngOnInit() {
sub.add(this.someService.em.subscribe(value => this.variableToChange = whatever));
}
Child.component.ts
constructor(someService: SomeService){}
ngOnInit() {
this.someService.em.next(true);
}
- 将变量作为输入从父项传递到子项,然后在子项中 init 更改该变量。
Parent.component.ts
variableToChange: any;
父组件.html
<child [variable]="variableToChange"></child>
Child.component.ts
@Input() variable: any;
ngOnInit() {
this.variable = 'whatever';
}
- 使用事件发射器
Child.component.ts
@Output() em: EventEmitter<any> = new EventEmitter();
ngOnInit() {
this.em.emit('something');
}
父组件.html
<child (em)="setVariable($event)"></child>
Parent.component.ts
variableToChange: any;
setVariable(event) {
this.variable = event; // event is emitted value
}