Search code examples
angularbooleancomponentshideshow

How to access boolean variable from one component inside app component - Angular


I have a scenario wherein i have multiple pages for which there is back arrow icon at application level across all forms. I am trying to set the back arrow in app.component.html as its common across all the forms. But some of the forms doesnt have back arrow. I need to hide back arrow only for those forms. In order to hide the back arrow for some forms(for eg., otp.component.ts), I have tried to match the url string name, and hide the back arrow if user reaches that specific form. This i am doing inside app.component. This doesnt work as the app component loads only once on load of the application.Is there any way to achieve this scenario.

May be I need to match the string logic inside otp.component.ts and pass the boolean value to app.component.html. But I am not sure how to achieve this.

Any help on this is much appreciated. Thanks.

app.component.html :

 <button class="header_back" *ngIf="showBackIcon" (click)="goBack()"></button>
    <button class="header_close" *ngIf="showCloseIcon" (click)="close()"></button>

app.component.ts:
 constructor() {
    const urlPath = window.location.href; 
    if (urlPath.indexOf("/otp") > -1) {
      this.showCloseIcon=true;
      this.showBackIcon=false;
    } else {
      this.showCloseIcon=false;
      this.showBackIcon=true;
    }
}

Solution

  • Create an injected service that carries out the path checking logic and assigns to a property within the service.

    That can then be accessed throughout the application by injecting in constructor so you can call it from other components and read the updated value in app.component e.g. this.backArrowService.showBackIcon

    new service back-arrow.service.ts:

    @Injectable()
    export class BackArrowService {
    public showBackIcon: boolean;
    //etc
    

    Any component:

    import { BackArrowService } from './back-arrow.service.ts';
    ...
    constructor(public backService: BackArrowService ) {}
    
    /*Example of directly updating value of service property which can be accessed 
    from other components that inject the service also*/
    ...
    ngOnInit() {
    this.backService.showBackIcon = true;
    }
    

    App component html:

    //See the value change:
    {{backService.showBackIcon}}
    
    <button class="header_back" *ngIf="backService.showBackIcon" (click)="goBack()"></button>