Angular change variable on component load
angular
Solution
Three ways to do it:
- Use BehaviorSubject, subscribe to it in parent and call `next` in child on init.
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);
}
- Pass variable from parent to child as input, then in child on init change that variable.
Parent.component.ts
variableToChange: any;
Parent.component.html
<child [variable]="variableToChange"></child>
Child.component.ts
@Input() variable: any;
ngOnInit() {
this.variable = 'whatever';
}
- Use EventEmitter
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
}
Problem
I have this ruote configuration: ``` const routes: Routes = [ { path: 'score', component: ScoreComponent } ]; ``` when the component score is loaded I want to change the value of a variable in parent component. The variable title is located in parent component template: ``` <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> ``` how can I do? I would like to use EventEmitter but I do not know how