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

Changing the value of a textarea in Angular forms using JavaScript

Having trouble with Angular forms? Try this: document.querySelector(TEXTAREA_SELECTOR).value = "some text" Methods like .title, .name, or .innerText don't seem to work. Consider trying these: document.querySelector(TEXTAREA_SELECTOR).dispa ...

A guide on renewing authentication tokens in the Nestjs framework

import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from './auth.service'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common&apo ...

Is there a way to create a TypeScript function that can accept both mutable and immutable arrays as arguments?

Writing the following method became quite complicated for me. The challenge arose because any method receiving the result from catchUndefinedList now needs to handle both mutable and immutable arrays. Could someone offer some assistance? /** * Catch any ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Utilizing a variable to pass props to a component (instead of a static component) within React Router 5

In react-router 5, you can pass props to a child component in this way: <Route path="/" exact render={ props => <MyPage title={myTitle} dataPath={myDataPath} {...props} />} /> However, I am using a route model in my ...

What is the method for launching Chrome synchronously in Selenium WebDriver using createSession()?

After executing the code below using Selenium WebDriver to launch a Chrome browser: import { Driver } from 'selenium-webdriver/chrome'; Driver.createSession(); console.log("I've launched!"); I'm encountering an issue where "I've ...

Ways to cancel a subscription once a specific parameter or value is met following a service/store interaction

I am working with a service that provides a changing object over time. I need to unsubscribe from this service once the object contains a specific property or later when the property reaches a certain value. In situations like these, I typically rely on t ...

The process of transitioning to a different view through a button press

How can I switch to another view by clicking a button in Aurelia? Here is my code: <button class="btn btn-success " click.delegate="save()">New item</button> Typescript configureRouter(config: RouterConfiguration, router: ...

Enhance user experience by implementing accessibility features in Angular 5 using

Our team is currently working on an Angular 6 application and we need to make it more accessible. I have tried adding aria-live="polite" to our angular-components, but we are experiencing issues with the Chromevox reader interrupting itself during data l ...

Exploring ways to interact with an API using arrays through interfaces in Angular CLI

I am currently utilizing Angular 7 and I have a REST API that provides the following data: {"Plate":"MIN123","Certifications":[{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"preventive","StartDate":"06 ...

What is the best way to organize checkboxes (either checked or unchecked) within a mat-table?

https://i.stack.imgur.com/cDQY7.png <ng-container matColumnDef="scheduled"> <th mat-header-cell mat-sort-header *matHeaderCellDef> Scheduled </th> <td mat-cell *matCellDef="let station"> ...

Adjust the column width in Angular material tables

Is it possible to adjust the width of individual columns? I've attempted various methods, but it appears that the columns are consistently equal in width regardless of any styles applied. ...

Change a Typescript class into a string representation, utilizing getter and setter methods in place of private variables

Below is a snippet of TypeScript code: class Example { private _id: number; private _name: string; constructor(id: number, name: string) { this._id = id; this._name = name; } public get id(): number { return t ...

Ways to relay information from the server to the client in a MEAN stack setup?

I'm a beginner with the MEAN stack app and encountering difficulties in sending data from the server to the front end. Currently, I can establish some communication between them, but that's about it. In the server, I have set up the JSON message ...

Importing custom pipes in Angular 2 becomes a bit tricky when working with data grouping

As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine. Here is an example of my JSON data: "locations": [ { "id": "ASS", "name": "test center", "city": "Staten Island", "zip": ...

Transfer dynamically generated table data to the following page

Seeking guidance on a common issue I'm facing. I am creating a table using data from Firebase upon page load, and I want users to click on a row to view specific details of that item. It may sound confusing, but it will make more sense with the code p ...

Issues with Cloud9 Angular and NodeJS connecting to API on a separate port of the same server

I am currently utilizing an AWS Cloud9 IDE for my project. Angular is running on port 8080, while my NodeJS (with Express) server is running on port 8081. In my Node app.js file, I have set up CORS headers as follows: const app = express(); app.use(expre ...

Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const refreshApi = createApi({ reducerPath: "apiSlice", baseQuery: fetchBaseQuer ...

Angular 5 experiences a single catchError event for two unsuccessful http calls

I recently implemented Observable.zip in my code to manage multiple observables concurrently. Observable.zip(observable1, observable2).subscribe(([res1, res2]) => doStuff()) The observables observable1 and observable2 represent HTTP requests, and I ha ...

When I try to use http-server with the port 8080, my Angular application is not being served. However, when

Upon opening my localhost, this is the view I encounter My goal is to create a Progressive Web App (PWA) using Angular. I meticulously followed the guidelines outlined on the angular.io site, yet it does not display the standard "Welcome to your app" page ...