Accessing Properties or Methods in Angular2 Components

My application consists of 3 main components: PageMenu, LoginSession, and LoginForm. The purpose is to establish a connection between the variables in LoginSession and PageMenu, allowing for the proper functionality of the LoginForm component.

PageMenu:


import {Component} from 'angular2/core';
import {LoginSession} from 'app/widgets/login-session/login-session';
import {LoginForm} from 'app/widgets/login-form/login-form';

@Component({
    selector: 'page-menu',
    templateUrl: 'app/widgets/page-menu/page-menu.html',
    directives: [ROUTER_DIRECTIVES, LoginSession, LoginForm]
})

export class PageMenu {

    loginFormVisible:boolean;

    constructor(private _router:Router) {
        this.loginFormVisible = false;
    }

    onClickNavbar(page) {
        this._router.navigate([page]);
    }

    triggerLoginForm() {
        this.loginFormVisible = LoginSession.loginFormVisibility;
    }
}

LoginSession:


import {Component} from 'angular2/core';

@Component({
    templateUrl: 'app/widgets/login-session/view/login-session.html',
    selector: 'login-session'
})
export class LoginSession {
    state:string;
    message:string;
    loginFormVisibility:boolean;

    constructor() {
        this.state = 'guest';
        this.message = 'Log in';
    }

    onClick() {
        switch (this.state) {
            case 'guest':
            {
                this.triggerLoginForm();
                break;
            }
        }
    }

    triggerLoginForm() {
        this.loginFormVisibility = !this.loginFormVisibility;
    }
}

LoginForm:


import {Component} from 'angular2/core';
import {FORM_DIRECTIVES,FormBuilder, Validators, ControlGroup, Control, NgClass} from 'angular2/common';
import {Output} from "angular2/core";

@Component({
    templateUrl: 'app/widgets/login-form/view/login-form.html',
    selector: 'login-form',
    directives: [FORM_DIRECTIVES]
})
export class LoginForm {
    state:string;
    message:string;


    loginForm:ControlGroup;
    login:Control = new Control("", Validators.required);
    password:Control = new Control("", Validators.required);


    constructor(formBuilder:FormBuilder) {
        this.loginForm = formBuilder.group({
            'login': this.login,
            'password': this.password,
        });
        console.log('LoginFORM!');
    }

    onSubmit() {
        document.cookie = "sessionId=123456789";
    }
}

Answer №1

Utilize a shared service for seamless communication and data sharing between components

export class LoginService {
  public loginChanged: EventEmitter<bool> = new EventEmitter<bool>();
}  
export class PageMenu {

  loginFormVisible:boolean;

  constructor(private _router:Router, private _loginService:LoginService) {
    this.loginFormVisible = false;
    this._loginService.loginChanged.subscribe(value => {this.loginFormVisible = !value;})
  }

  ...

}

The LoginForm can retrieve the value in a similar manner.

export class LoginSession {
  state:string;
  message:string;
  loginFormVisibility:boolean;

  constructor(private _loginService:LoginService) {
    this.state = 'guest';
    this.message = 'Zaloguj się';
  }

  onClick() {
    switch (this.state) {
      case 'guest':
      {
        this.triggerLoginForm();
        break;
      }
    }
  }

  triggerLoginForm() {
    this.loginFormVisibility = !this.loginFormVisibility;
    this._loginService.loginChanged.next(this.loginFormVisibility);
  }
}

Ensure registration exclusively within bootstrap() to obtain a single application-wide instance:

bootstrap(AppComponent, [LoginService])

For further information, refer to Global Events in Angular 2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TypeORM's Polymorphic Relationship fails to retrieve data from the parent entity

Currently, I am utilizing https://github.com/bashleigh/typeorm-polymorphic for handling polymorphic relations in my model. There are several models involved: // Device Entity @Entity() @TableInheritance({ column: { type: 'varchar', name: 'ty ...

Storing and Retrieving User Identifiers in Next.js

Currently, I am developing a project using Next.js and I have the requirement to securely store the userId once a user logs in. This unique identifier is crucial for accessing personalized user data and creating dynamic URLs for the user profile menu. The ...

Displaying a component upon clicking a button in Angular 9

Within the navbar, there is a "+" button that triggers the display of the component. <app-navbar></app-navbar> Upon clicking the button, the <app-stepper></app-stepper> component should be shown. <app-navbar></app-navba ...

Repetitive execution of Angular service function upon route change

In my Angular 8 project, there is a service function responsible for copying data. However, I encountered an issue where if I copy the data on a page, navigate to another page, and then return to the original page to copy the data again, it ends up duplica ...

Is it feasible to have two interfaces in Typescript that reference each other?

I am facing an issue with two interfaces, UserProfile and Interest. Here is the code for both interfaces: export default interface UserProfile { userProfileId: string, rep: number, pfpUrl: string, bio: string, experience: "beginner" | " ...

best practices for running callbacks in sequence within Angular

Seeking a solution to ensure Angular waits for data fetching to complete before proceeding with execution in ngOnInit: fetchData() { console.log('2') this.http.get("http://jsonplaceholder.typicode.com/users").subscribe( (data) =&g ...

Loading an entity from a service within an *ngFor loop: A step-by-step guide

Suppose I have a scenario where I need to display a list of students in Angular2. The data is fetched from a java backend using a service, and the fields are: id name age field universityId However, when displaying this data on my webpage, I want to sho ...

Ways to expand the width of mat-dialog-actions component in Angular 8

Is there a way to make the cancel and save buttons in the dialog window take up the entire available space? If anyone has any suggestions on how to achieve this, please let me know! ...

What potential issues should I be aware of when I install new node packages?

I encountered an error message when trying to install a Node Package. Running npm install shows that everything is up to date. https://i.stack.imgur.com/d78hf.png ...

Using Vuelidate with Vue 3, vue-class-component, and TypeScript combination

Is there anyone who has successfully implemented Vuelidate with Vue 3 using the Composition API? Although Vuelidate is still in alpha for Vue 3, I believe that if it works with the Composition API, there must be a way to make it work with classes as well. ...

Angular 4 and Web API 2 encounter an error with preflight response having an invalid HTTP status code of 404

I am currently utilizing a Web API(2) service hosted on a different server from my Angular 4 frontend application to retrieve specific information. To access the action method, authorization is required and I achieve this by using an access token obtained ...

Is there a method to automatically eliminate all unnecessary properties in an Angular project?

In my extensive Angular project, I suspect that there are numerous declared properties in .component.ts that are not being used. Is there a method available to automatically eliminate all unused properties within an Angular project while also taking into ...

Using Ionic to send email verification via Firebase

I have encountered an issue while attempting to send an email verification to users upon signing up. Even though the user is successfully added to Firebase, the email verification is not being sent out. Upon checking the console for errors, I found the f ...

Error TS2532 in TypeScript indicates that there is a possibility that the object is undefined

Yesterday, WebStorm 2020.1 was installed on my computer. All of a sudden, I started encountering numerous TS2532 errors. How is it even possible for this to be "undefined"? Doesn't selectedOwner && prevent that? I attempted to eliminate thi ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...

What are the steps to extract information from an observable?

Having trouble retrieving data from a request? I've encountered an issue where the data retrieved inside .subscribe in an observable function is returning as undefined when trying to access it outside the function. It's quite frustrating! Here i ...

There is a method in TypeScript called "Mapping IDs to Object Properties"

I'm currently developing a React app that features several input fields, each with its own unique id: interface IFormInput { name: string; surname: string; address: string; born: Date; etc.. } const [input, setInput] = useState< ...

Fixing the issue "Unable to access property 'toDataURL' of undefined" in the Angular2 signaturePad

I am currently developing a project using Angular 7 and I am facing an issue with implementing signature functionality. I decided to use the "angular2-signaturepad" package for this purpose, and everything is working smoothly until the user completes drawi ...

Having trouble with CSS Locator identifying an element in your Protractor Test?

In the Protractor test snippet below, I am attempting to calculate the quantity of div elements using the CSS locator: let list = element.all(by.css('div[class="ag-header-cell ag-header-cell-sortable"]')); expect(list.count()).toBe(11); ...