0

I'm looking for solution where I can switch dynamically (depending on the component we are in) value in parent component. Value should be different in each component.

Is the service not too much for this kind of solution? Is there a simpler solution in Angular?

Parent - Some text {{ title }}

Child1 - title = "title one" Child2 - title = "title two"

etc.

Forey
  • 81
  • 7

2 Answers2

2

Try using EventEmitter:

child-component.ts

import { Output, EventEmitter } from '@angular/core'; 
title: string;
@Output() titleChange: EventEmitter<any> = new EventEmitter();

ngOnInit() {
  this.title = 'child title';
  this.titleChange.emit(this.title);
}

parent-component.html

<p>{{title}}</p>
<app-child (titleChange)="onTitleChange($event)"></app-child>

parent-component.ts

title: string

onTitleChange(value: string) {
   this.title = value;
}
glinda93
  • 7,659
  • 5
  • 40
  • 78
  • I used that solution. But Angular where throwing error every time it switch "panel" so I have to add onTitleChange(value: string) { setTimeout(()=>{ this.title = value; }); – Forey Jul 06 '20 at 13:46
0

Are you using the RoutingModule? If yes, you could add a data attribute (i.e. title) in your routing definition and then subscribe to route changes in the parent component.

For example like this: https://stackoverflow.com/a/58863966/3073719

Martin
  • 63
  • 6