How to use a variable from a component in another in Angular2

前端 未结 3 1964
说谎
说谎 2020-12-31 12:09

I was wondering if it is possible to use variable values from one component into another one without having to use the template of the first one, just need the value of the

相关标签:
3条回答
  • 2020-12-31 12:11

    Yes possible, you can use the @Input() method or use write get method like below

    export class Demo {
        const sum = 10;
    
        get SumValue() {
            return this.sum;
        }
    }
    

    import-->Demo

    export class Demo2 {
       private sum: number;
       this.sum = Demo.SumValue();
    }
    
    0 讨论(0)
  • 2020-12-31 12:16

    I was developing a thing and I faced the same challenge. My approach.

    I had two different components and a service.

    loginComponent, headerCompnent and a loginauth service.

        validateUser(name,pass){
    
       this.loginStatus = this.loginauth.validateUser(name,pass);
    
       if(this.loginStatus) this.route.navigate(['/welcome']);
       else this.route.navigate(['/login']);
    
      }
    

    image from LoginComponent

    I wanted to use "loginStatus" in headerComponent.

    this.loginauth.validateUser(name,pass); loginauth was the service and validateUser(...) method inside it.

    So I created a static variable inside the service and inject that service into both components and by injecting the same service in headerComponent I was able to retrieve the value of that static variable.

    In service, create and initialize it as per your requirement.

    static loginFlag = false;
    

    loginAuth service img

    In header component.

    Import that service and access that static variable with class name.

     LoginAuthService.loginFlag
    

    headerComponent img

    0 讨论(0)
  • 2020-12-31 12:26

    Go to your app.module.ts and make the provider of that component you want to inherit with other classes:

    Then go to the class you want access of that variable, and import the component into that:

    Make the constructor of it:

    And happily get access to the variables:

    0 讨论(0)
提交回复
热议问题