Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular display title of selected component

My question is quite simple.

My structure

In the router-outlet I display my pages for example /contact, /home or /meetus

(How) can I display the name of the active component in the {{title}}?

Is this even possible or do I have to move my title bar inside every component?

like image 981
Roboneter Avatar asked Dec 18 '22 22:12

Roboneter


2 Answers

You can create a an AppService which holds the application title and provides it as an observable (with accessor method such as get and set).

@Injectable()
export class AppService {
  private title = new BehaviorSubject<String>('App title');
  private title$ = this.title.asObservable();

  constructor() {}

  setTitle(title: String) {
    this.title.next(title);
  }

  getTitle(): Observable<String> {
    return this.title$;
  }
}

Then in a component (let's say the AppComponent) which will hold (and show) the title, you subscribe to the appService#getTitle() method and update the title property accordingly.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title: String;

  constructor(private appService: AppService) { }

  ngOnInit() {
    this.appService.getTitle().subscribe(appTitle => this.title = appTitle);
  }
}

Now in every component you inject the AppService (when needed to update the title) and call the appService#setTitle(). For example, a hello component:

@Component({
  selector: 'hello',
  template: `<p><b>Hello</b> component content</p>`,
  styles: []
})
export class HelloComponent  {
  
  constructor(private appService: AppService) { }

  ngOnInit() {
    this.appService.setTitle('Hello Component');
  }
}

See this Working Demo (Tested with Angular 6)

like image 178
lealceldeiro Avatar answered Dec 28 '22 10:12

lealceldeiro


You can use the Angular titleService to display the page title in the header component like below:

Header component .ts:

export class AppComponent {
  public constructor(private titleService: Title ) { }
}

Header component .html:

<div class="title-bar">
    {{titleService.getTitle()}}
</div>

Then in any component you can set the page title using the Angular titleService and it will automatically change in the title and header sections:

export class AppComponent implements OnInit { {
  public constructor(private titleService: Title ) { }

  ngOnInit() {
    this.titleService.setTitle("Component's title");
  }
}
like image 40
Ali Rida Avatar answered Dec 28 '22 09:12

Ali Rida