I have been working an app with Angular 8.
I am currently trying to set the page title from the router. For this purpose, in app.module.ts
I have:
In app.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor() {}
public title: String = 'Employees';
changeTitle(val: String) {
this.title = val;
}
}
In app.component.html
:
<app-navbar></app-navbar>
<div class="container">
<h1 class="mt-2 mb-3">{{ title }}</h1>
<router-outlet (onSetTitle)="changeTitle($event)"></router-outlet>
</div>
In employee-details.component.ts
:
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Employee } from '../../models/empModel';
import * as data from '../../data/employees';
@Component({
selector: 'app-employee-details',
templateUrl: './employee-details.component.html',
styleUrls: ['./employee-details.component.css'],
})
export class EmployeeDetailsComponent implements OnInit {
constructor(private ActivatedRoute: ActivatedRoute) {}
@Output() onSetTitle = new EventEmitter<String>();
public empsArray: Employee[] = data.employees;
public employee: any = {};
public setTitle() {
console.log(this.ActivatedRoute.snapshot.data['title']);
this.onSetTitle.emit(this.ActivatedRoute.snapshot.data['title']);
}
public getEmployee() {
const empno = Number(this.ActivatedRoute.snapshot.paramMap.get('empno'));
this.employee = this.empsArray.find((item) => item.empno == empno);
}
ngOnInit() {
this.setTitle();
this.getEmployee();
}
}
Stackblitz
I have put together a Stackblitz too.
The problem
The initial value of the title
variable does not change, after navigating to the EmployeeDetailsComponent
even though the setTitle()
method does return the correct value for the title
variable.
Questions
- What am I doing wrong?
- What is the most reliable way to fix this issue?