0

I am basically able to completely hide a component, but I do not know how I can hide or show an element of a component.

export class AppComponent  {
  headerFooterVisible: boolean;
  constructor(private router: Router){
    router.events.subscribe(e => {
    if(e instanceof NavigationEnd){
      if(e.urlAfterRedirects != '/'){
        this.headerFooterVisible= true;
      }else{
        this.headerFooterVisible= false;
      }

    }
  });
  }
  name = 'Angular 4';
  private activatedComponent;
  onActivate(component){
    this.activatedComponent = component;
  }


<menu *ngIf="headerFooterVisible"></menu>
<router-outlet (activate)='onActivate($event)'></router-outlet>
<footer *ngIf="headerFooterVisible"></footer>

I want the variable {{headerFooterVisible}} to be shown in each of my components in real time. how can I do it?

this is my code:

https://stackblitz.com/edit/angular-m6ffqn?file=app/another.component.ts

Azer
  • 1,200
  • 13
  • 23
yavg
  • 2,761
  • 7
  • 45
  • 115

2 Answers2

0

You can create service using BehavoirSubject which it will store the value from headerFooterVisible. In componenets where you want to access to headerFooterVisible you can subscribe this service in ts and get value or use async pipe in html.

For example - CacheService:

export class CacheService {

  readonly headerFooterVisible$: Observable<boolean>;
  private headerFooterVisibleSubject: BehaviorSubject<boolean> = new BehaviorSubject(false); // this place you can set first value, you can choose true or false

  constructor() {
    this.headerFooterVisible$ = this.headerFooterVisibleSubject.asObservable();
  }

  addNewValueToSubject(value: boolean) {
      this.headerFooterVisibleSubject.next(value);
  }
}

In components you have to inject this service.

constructor(private cacheService: CacheService) {}

When you want to get value:

this.cacheService.headerFooterVisible$.subscrive((value: boolean) => console.log(boolean);

and add new value:

this.cacheService.addNewValueToSubject(this.headerFooterVisible);

You remember about takeUntil.

0

If I understand your question right you can just use

[hidden]="headerFooterVisible"

For more about hidden: What is the equivalent of ngShow and ngHide in Angular 2+?

DEVolkan
  • 572
  • 5
  • 7