0

How to call one component methods to another component in angular 2/4/6. I am using two components one is login and another one is register. In login component i have one method

login()
    {
    var email = email;
    console.log("username", email);
    var password = password;
    this.loginService.loginrequest(email, password).subscribe(
          data => {console.log(data)});
    }

So how to this login method in registration component?

Nihal
  • 5,262
  • 7
  • 23
  • 41
sai kumar
  • 1
  • 1

2 Answers2

1

I would suggest extracting this method to a shared service.

@Injectable()
export class AuthService {   
  public login(login: string, password: string) {...} 
}

https://angular.io/guide/architecture-services

tplk
  • 11
  • 2
0

You have to do below changes

1. registration.component.ts

import { LoginComponent } from 'mention your path';

You have to create instance of your component in your constructor.

constructor(private logComponent: LoginComponent) {

}

Now, you can access loginComponent methods I am giving one example

ngOnInit() {
this.logComponent.login();
}

You can use in above way.

Flutterian
  • 1,761
  • 1
  • 21
  • 47
  • I am implemented same code import { FuseLogin2Component } from '../login/login-2.component'; constructor(private loginComponent: FuseLogin2Component){} updatePassword() { this.loginComponent.login(); } – sai kumar Jul 16 '18 at 09:01
  • I am getting this error ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[UpdateForgetpasswordComponent -> FuseLogin2Component]: – sai kumar Jul 16 '18 at 09:03
  • That's because you might have forgot dependency injection. You have to declare your component in app.module.ts file also. Please check this link. https://stackoverflow.com/questions/49776562/uncaught-in-promise-error-staticinjectorerrorappmoduleoptions – Flutterian Jul 16 '18 at 09:29