Step-by-step guide on updating the home page content in angular4 upon signing up with the user page

The home page and user page contents are both displayed on the home page itself. In the header section, I have a SignIn and SignUp form from the home.html file. Additionally, there is another Signup form from the user page. This form includes 3 buttons: one for signing up with Facebook, another for signing up with Google, and the third for traditional SignUp using name, email, and password. When signing up using either Facebook or Google, the content of the home page changes dynamically from "SignIn and SignUp" to "User and SignOut," while hiding the SignUp form from the user page.

However, this functionality does not work as expected when just using the regular SignUp process with name, email, and password.

I have attempted to use an emit emitter as well, but it doesn't seem to work with the standard SignUp method. Can anyone provide guidance?

Home.html:

<ul>
<li class="signUp" *ngIf = "loggedIn">{{userName}}</li>
<li class="signIn" (click)="signOut()" *ngIf = "loggedIn">Sign Out</li>
<li class="signUp" (click)="openSignUp(user)" *ngIf = "!loggedIn">Sign Up</li>
<li class="signIn" (click)="openSignIn(logedin)" *ngIf = "!loggedIn">Sign In</li>
</ul> 

User.html:

<div class="favorite" *ngIf="!loggedIn">
    <h1>User</h1>
    <hr />
    <div class="backImage">
      <form name="signUpForm" class="signUpForm" #signUpForm="ngForm" novalidate>
        <div class="form-group">
          <h3>Sign Up</h3>
        </div>
        <div class="form-group input">
          <mat-form-field> 
            <mat-icon>perm_identity</mat-icon>
            <input matInput type="text" placeholder="Name" name="name" [(ngModel)]="name" #Name="ngModel" required>
          </mat-form-field>
        </div>
        <div class="form-group input">
          <mat-form-field> 
            <mat-icon>email</mat-icon>
            <input matInput type="email" placeholder="Email" name="email" [(ngModel)]="user.email" #Email="ngModel" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" required>
          </mat-form-field>
        </div>
        <div class="form-group input">
          <mat-form-field> 
            <mat-icon>lock</mat-icon>
            <input matInput type="password" placeholder="Password" name="password" [(ngModel)]="user.password" #Password="ngModel" required>
          </mat-form-field>
        </div>          
      </form>
    </div>
  </div>

User.ts:

this.ApiService
      .checklogin()
      .subscribe(
        user => {
          this.loggedIn = localStorage.getItem("loggedin");
          this.user_id = user.data[0].user_id;
          this.userName = user.data[0].name;
        }, error => {
          console.log(error);
        });

      newUser(user, _id) {
        this.isLoadingSignUp = true;
        user.role_id = this._id 
        var data = {
          "user":{
          email:user.email,
          password:user.password,
          active:user.active,
          role_id:this._id,
          name:user.name
           }     
        }
        this.ApiService
            .signUp(data)
            .subscribe(
              signUser => {
                  this.userName = user.name;
                  localStorage.setItem('loggedin', 'true');
                  this.loggedIn = true;
                  this.isLoadingSignUp = false;
                  this.router.navigate(['/home']);
                  this.toasterService.pop('success', 'SignUp Successfully');
                  this.ApiService.getUserData(user.data);
               }, error => {
                  this.isLoadingSignUp = false;
                  this.ApiService.getUserData(error);
                  if(error.data && error.data.length > 0) {
                    this.toasterService.pop('error', error.data);
                  } else {
                    this.toasterService.pop('error', 'Something went wrong!');
                  }
               })
      }

Answer №1

To establish communication between different components, you can utilize Observable and subject.

The recommended approach is to achieve this using a service.

Begin by creating a service named SignUpService that initializes a new subject to indicate signing in status.

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class SignUpService {
  private signInSource = new Subject<string>();

  signinDone$ = this.signInSource.asObservable();

  signIn() {
    this.signInSource.next();
  }
}

Invoke the subject within the signIn component

import { SignInService }     from './signin.service';

@Component({
})
export class SignInComponent {
    this.SignInService.signIn();
}

Receive and handle the event in the Header component

import { SignInService }  from './signin.service';
import { Subscription }   from 'rxjs/Subscription';

@Component({
})
export class HeaderComponent implements OnDestroy {
  subscription: Subscription;

  constructor(private signInService: SignInService) {
    this.subscription = signInService.signinDone$.subscribe(
      signin => {
        alert('came here')
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Answer №2

For your specific needs and project organization, utilizing your browser can be beneficial. This involves saving a distinct value in the browser's local storage each time a user signs in or signs up using Facebook or Google. This saved value can then be retrieved and utilized to determine the source of the user's login. By incorporating this value into ngIf conditions, you can control when certain elements are displayed on the page.

I trust you grasp the concept I am trying to convey.

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

Troubleshooting the issue with utilizing the ng-repeat directive to loop through images in Angular JS

Embarking on my initial website development journey with Java and Spring Boot, I've hit a stumbling block in the front-end realm. Being a newbie, I'm struggling to identify and resolve the issue at hand. Problem title: How do I ...

discord.js: Bot keeps sending duplicate embeds

I recently set up my discord bot to respond with a message when I enter a specific command, but I've run into an issue where it's sending the same embed twice. I've tried troubleshooting, but so far I haven't been able to pinpoint the c ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

The individual is currently tracking his own movements

When developing a function to handle user following and unfollowing, I encountered an issue where the code checking if a user can follow themselves was not functioning as expected. Despite implementing an if statement to prevent self-following, users were ...

What is the best way to create an interface tailored to a specific scenario using TypeScript?

In my TypeScript project without React, I am dealing with an interface structured like this: export interface LayerStyling<T> { attribute: string; value: AllowedTypes; type: LayerTypes; layout?: { icon: string }; state ...

Add the user's input text to a modal in C# MVC 5

If my status changes, I want to add another text box or text area for additional comments. In the photo provided, this has been implemented but the positioning is not quite right due to issues with the modal. Below is a snippet of my code where you can ta ...

Displaying Date in Angular 2 Application with Proper Formatting

I'm currently working on formatting the date pipe in my Angular application to display correctly when used within an input template. Originally, without the date formatting, my code looked like this: <input class="app-input" [readonly]="!hasAdminA ...

Testing HTTP Requests in Angular applications

I am currently utilizing Angular 9+. When it comes to unit testing services that utilize httpClient for making http requests, I found the official documentation from the Angular Team to be very helpful. By following their guidelines, I was able to success ...

Is it possible to customize the deep elements of ExpansionPanelSummary using styled-components in React?

After digging into the documentation and examples on how to customize Material UI styling with styled-components, I successfully applied styling to the root and "deeper elements" within an ExpansionPanel and ExpansionPanelDetails. However, when attempting ...

const error = new TypeError(`${calculateRelativePath(cwd, fileName)}: Skipping emission of file`);

Hey there! I have a typescript code snippet that looks like this: import { getConnection } from "typeorm"; import { GraphQLClient } from "graphql-request"; import got from "got"; import database from "./utils/database&quo ...

"Sending a file (Image) through NextJS API Routes to an external API: A step-by-step guide

I am currently using a combination of NextJS (SSR and SPA for authorized dashboard) with Django Rest FW on the backend. To handle authentication, I employ JWT tokens stored in cookies. As a result, it is necessary to have a middleware at /pages/api/* that ...

Namespacing is not applied to dynamic modules in Vuex

I've been tackling a modular vue application that enrolls the modules during compile time. Take a look at the code snippet below - app.js import store from './vue-components/store'; var components = { erp_inventory: true, erp_purc ...

Is it possible to employ a method to eliminate a specific valuable element 'this' from an array?

I am working on a task management app that allows users to create a To-Do list and remove specific items from the list. Currently, I am facing an issue with using 'localStorage' to save the list when the page is refreshed. The problem arises when ...

How can you swap out a forward slash in vue.js?

I am facing a coding issue that I need help with: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the numbers in my item.id contain slashes, leadin ...

What is the best method to eliminate the 'Unsorted' selection from the sorting options in Material React Table?

Currently utilizing the "material-react-table" library within a React JS project. In alignment with my needs, seeking to eliminate the 'Unsorted' sorting option in Material React Table. Could someone assist me in addressing this? Your help is ...

Exploring AngularJS's capabilities with asynchronous tasks

I am in the process of developing a simple app using AngularJS. One of the key functionalities I am working on is removing items from a list. To achieve this, I have created the following code snippet: $scope.removeItem = function(item) { var toRemove = ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

Unveil the path as you scroll

Currently, I am tasked with creating a dynamic timeline that has animations triggered by scrolling. As part of this project, I must also reveal a pathway as the user scrolls - this pathway consists of circular shapes. The challenge lies in revealing an im ...

Angular is unable to create a new project

I attempted to create a new project using AngularCLI in the following way: ng new my-app-ambition However, this resulted in the following errors: npm WARN registry Unexpected warning for https://registry.npmjs.org/: Miscellaneous Warning UNABLE_TO_VER ...

Is there a Javascript tool available for creating a visual representation of the correlation between items in two separate

Does anyone have recommendations for an HTML/JavaScript/browser-based component that can map items in one list to another? Imagine a scenario where there is a list of items on the left-hand side and another list on the right, with the ability to click on a ...