Three ways to do this:
- Use a BehaviorSubject, subscribe to it in the parent element and call
nextinit in the child element.
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 the variable from parent to child as input, and then change this variable in child on init.
Parent.component.ts
variableToChange: any;
Parent.component.html
<child [variable]="variableToChange"></child>
Child.component.ts
@Input() variable: any;
ngOnInit() {
this.variable = 'whatever';
}
- 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;
}