我有这个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>
我该怎么办?
我想使用EventEmitter,但我不知道如何
答案 0 :(得分:3)
三种方法:
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);
}
Parent.component.ts
variableToChange: any;
Parent.component.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');
}
Parent.component.html
<child (em)="setVariable($event)"></child>
Parent.component.ts
variableToChange: any;
setVariable(event) {
this.variable = event; // event is emitted value
}