Search code examples
angularangular2-routingangular2-servicesangular2-components

service to access and update the variable in angular 2


I have variable authentication which i set the false like this in app root component

 import { Component ,Input} from '@angular/core' ;


 @Component({
 selector: 'app-root',
 templateUrl:'./app.component.html',
 styleUrls: ['./app.component.css']

})
export class AppComponent {
  authenticated = false;


}

I have used the component routing in angular 2 using layout my html code for this is

        <app-nav-menu *ngIf="!authenticated"></app-nav-menu>

</div>

<div [ngClass]="{'campaign-process':authenticated}" >

    <app-side-menu *ngIf="authenticated"></app-side-menu>
<div [ngClass]="{'campaign-content':authenticated}">

    <app-upr-div-seach *ngIf="authenticated"></app-upr-div-seach>

    <router-outlet></router-outlet>


</div><!--campaign content-->

i want to update this authentication variable in child component (login component) some can please make a service for sharing and accessing this in child component how can i do this thanks in advance

Edited ths is component file

  import { Component, Input } from '@angular/core';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})
export class LoginComponent  {





  clickedLogin(event)
  {
  console.log('here i want to update this ');

  }

 }

Solution

  • You can make a service to update the variable as follows,

    @Injectable()
    export class sharedService {
     authenticated :boolean;
     constructor() {
    }
     Initialize() {
        this.authenticated = false;
    }
    
     Update(input:any) {
        this.authenticated = input;
     }
    }
    

    Make sure to inject to your module, later you can call the method Update and Initalize to do whatever you need.

    Then in Component1.ts

    import { sharedService } from '/services/sharedService.service';
     constructor( private sharedSer : sharedService ) {
    
        }
    
    Update(){
      this.sharedSer.Update(yourvalu);
    }