0

I have a shared component - headerbarComponent - with a property - headerTitle. I use it to show which page is current. And I need to change this title depneding on a loaded template. Onсe a new component loaded it calls the method

headerbarComponent.setTitle( newTile ) { this.headerTitle = newTitle }

It shows in JS console that the title is changed but there's no changes at the header at all.

<div>{{headerTitle}}</div>

How do I change this title?

1 Answers1

1

You can create a service with a new Subject() that will "watch" for any changes:

@Injectable()
export class HeaderService {

  private headerTitleSubject: Subject<string> = new Subject<string>();

  constructor() { }

  setTitle(title: string) {
    this.headerTitleSubject.next(title);
  }

  onSetTitle() {
    return this.headerTitleSubject;
  }
}

Your shared component needs to subscribe to it and to update your title:

this.headerService.onSetTitle().subscribe(
    newTitle => {
        this.title = newTitle;
    }
);

And the easiest part is to update this title from any component that you want:

updateTitle() {
    this.headerService.setTitle('Home title');
}

Here is a working example: https://plnkr.co/edit/f8vmbd30K6tzBZyPFJLS?p=preview

Hristo Eftimov
  • 13,845
  • 13
  • 50
  • 77