Answer the question
In order to leave comments, you need to log in
How to implement one common header for all pages in Angular?
Hello! I am learning Angular and it became necessary to have one common site header for all pages, where, depending on the current route, the header title and available buttons would change. Moreover, the buttons perform the functions of a component that was loaded through a <router-outlet></router-outlet>
particular route.
I read somewhere that in such situations the best solution would be to create a service, but I don’t quite understand how to implement it, in the sense that when I go to other pages, my buttons and title would also be automatically updated ... I used BehaivorSubject 's, but this does not help me much, and now I can't hang on any of my BehaivorSubject whims ..?!
Here is what my implementation and structure looks like at the moment:
<!-- ===== [MAIN] ===== -->
<div class="main">
<!-- ========== [Общая шапка] ========== -->
<div *ngIf="headerVisibility">
<div class="header">
<h2 class="heading_text">{{ЗДЕСЬ_БЫ_ПОДСТАВЛЯЛСЯ_ЗАГОЛОВОК}}</h2>
<div class="header_buttons">
<button
*ngFor="let btn of МАССИВ_ВСЕХ_ДОСТУПНЫХ_КНОПОК_ПО_ТЕКУЩЕМУ_РОУТУ(editUser(), addUser())"
class="{{btn.НАЗВАНИЕ_КЛАССА_КНОПКИ}}"
(click)="btn.ФУНКЦИЯ_ИЗ_ВСТАВЛЯЕМОГО_ПО_РОУТУ_КОМПОНЕНТА()"
title="{{btn.НАЗВАНИЕ_КНОПКИ}}"
></button>
</div>
</div>
</div>
<!-- Вставляемый по роуту компонент -->
<router-outlet></router-outlet>
</div>
import { Component, OnInit } from '@angular/core';
import { HeaderService } from '@app/shared/services/header.service';
@Component({
selector: 'app-main'
templateUrl: './main.component.html',
styleUrls: ['./main.component.less']
})
export class MainComponent implements OnInit {
title: string; // текущий заголовок хэдэра
headerVisibility: boolean; // текущее состояние отображения хэдэра
headerButtons = new Array<Object>(); // текущий набор кнопок хэдэра
constructor ( private headerService: HeaderService ) { }
ngOnInit() {
// подписываемся на объекты, чтобы отлавливать изменения
this.headerService.visibility.subscribe((newMode: boolean) => {this.headerVisibility = newMode});
this.headerService.title.subscribe((newTitle: string) => {this.title = newTitle});
this.headerButtons = this.headerService.getButtons(); // получаем массив кнопок
}
}
import { Component, OnInit } from '@angular/core';
import { HeaderService } from '@app/shared/services/header.service';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.less']
})
export class UsersComponent implements OnInit {
constructor ( private headerService: HeaderService ) { }
ngOnInit() {
this.headerService.addButton(this.addUser.bind(this), 'add_button_class', 'MyButtonTItle');
}
editUser(id: number) {
console.log('EDITING_USER_HERE');
}
addUser() {
console.log('ADDING_USER_HERE');
}
}
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HeaderService
{
constructor(){}
visibility = new BehaviorSubject<Boolean>(true); // видимость header'a как такового
title = new BehaviorSubject<String>('Заголовок хэдэра по умолчанию'); // заголовок
buttons = new Array<Object>(); // кнопки
addButton(buttonFunc: Function, className: string, title: string) {
this.buttons.push({
buttonFunc,
className,
title
});
}
getButtons() { // чтобы получить массив объектов с информацией о кнопках
return this.buttons;
}
}
Answer the question
In order to leave comments, you need to log in
step 1. You make a service where you store data
private data = new BehaviorSubject(null);
setData(data) { this.data.next(data) }
selectData() { return this.data.asObsevable() }
data = this.myService.selectData()
<p> {{ data | async }} <p>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question