Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet:

<div *ngIf="authorized; then picUrl else login"></div>

                <ng-template #login>
                    <button mat-raised-button color="accent" class="mdl-cell mdl-cell--12-col mdl-color-text--white" style="background: #033342" (click)="openDialog()">Login</button>
                </ng-template>
                <ng-template #picUrl>
                    <img src="{{_loginVM.profilePic}}" class="img-thumbnail" alt="profile pic">
                </ng-template>

Initiating the social component:

<social></social>

App.component.ts

export class AppComponent {
    public authorized: boolean = false;
}

Social component.ts

import { AppComponent} from '../app/app.component'

export class SocialComponent {
    private _appComponent: AppComponent;
    constructor(private socialAuthService: AuthService, appComponent: AppComponent,
        public dialogRef: MatDialogRef<SignInSignUpDialogHomeComponent>) {
        this._appComponent = appComponent;
    }
 public socialSignIn(socialPlatform: string) {
        let socialPlatformProvider: any;
        if (socialPlatform == "facebook") {
            socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
        } else if (socialPlatform == "google") {
            socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
        }

        this.socialAuthService.signIn(socialPlatformProvider).then(
            (userData) => {
                if (userData != null) {
                    this._appComponent.authorized = true;
                    this._appComponent._loginVM.profilePic = userData.image;
                    this.dialogRef.close();
                }
            }
        );
    }

Once a successful login occurs, the value

this._appComponent.authorized = true;
gets updated. However, this change is not reflected in the UI/UX.

Further information can also be found here

I have attempted using BehaviorSubject<boolean>, but I am unsure how to subscribe to the UI data bind. Is this the correct approach, or is there a way to directly update the component variable?

Answer №1

.html

<div *ngIf="authenticatedUser; then displayImage else showLogin"></div>

component.ts

ngOnInit() {
this.authenticatedUser = this.authService.isLoggedIn;
}

service.ts

get isLoggedIn(): boolean {
    return this.currentUser != null; //You can choose to return true or false
 }
get currentUser(): user{
  let user = localStorage.getItem('details')
return user;
}

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

Enhance user experience with Telerik RadGrid's seamless integration of client-side pagination for

My web service provides me with data that I process before using it as a datasource for my RadGrid (Telerik). The dataset is quite large, prompting me to consider implementing pagination. However, when attempting server-side pagination, I encountered some ...

Craving assistance in coding permutations

Thank you for responding. I want to express my gratitude for your efforts in trying to assist me. Unfortunately, I have posted this problem on multiple websites and no one has been willing to help. Regarding my code, my objective is to count permutations. ...

retrieve the most recent file following a $group operation

I am currently utilizing the official MongoDB driver specifically designed for Node.js. This is how my message data is organized. Each post consists of a timestamp, a user ID, and a topic ID. [ { "_id" : ObjectId("5b0abb48b20c1b4b92365145"), "t ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

When converting to TypeScript, the error 'express.Router() is not defined' may

Currently, I am in the process of converting my express nodejs project from JavaScript to TypeScript. One of the changes I've made is renaming the file extension and updating 'var' to 'import' for "require()". However, there seems ...

Error: The attempt to access the 'useContext' property of null has failed due to a TypeError

Nowhere in my React code am I using the useContext property. There is a compiled webpack file in an npm package with a component inside. When trying to use this component in my React app, it throws an error: Uncaught TypeError: Cannot read properties of nu ...

In TypeScript, it can be challenging to determine the equality between a value and an enum

I am encountering an issue with my simple code: enum Color { BLUE, RED } class Brush { color: Color constructor(values) { this.color = values.color } } let JSON_RESPONSE = `{"color": "BLUE"}` let brush = new Brush(JSON.parse(JSON ...

What are the steps to develop an ElectronJS application that displays "Hello world!" in the console after a button click?

Can anyone offer a helping hand? From the depths of imagination to the realms never before conceived by humans. Check out this HTML snippet: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hell ...

Implement a FOR loop in conjunction with an AJAX request

My goal is to send an AJAX request with multiple form fields and use an array for validations. I would like to also pass these values via AJAX: Although I haven't used a for loop in JavaScript before, it looks familiar. The current approach of the l ...

NuxtJS using Babel 7: the spread operator persists in compiled files

Struggling to get my NuxtJS app functioning properly on IE11. Despite multiple attempts to configure Babel for compatibility, spread operators are still present in the built pages files, suggesting that Nuxt code is not being transformed correctly. Below ...

The readonly property of the ng2-currency-mask <input> element is not functioning properly

Seeking assistance with an input field that requires users to enter monetary values. I am utilizing ng2-currency-mask for this purpose, but I also need the input to be read-only. Adding the readonly attribute did not resolve the issue as the value still ch ...

Display JSON data in a hierarchical tree structure using AngularJS

Looking to display three nodes of a JSON file as a tree using AngularJS. The nodes are data.key, data.parentItem, and data.title. Below is the JavaScript code: var phonecatApp = angular.module('myApp', []) phonecatApp.controller('myContr ...

Stopping the animation of scrollLeft upon user interaction can be achieved by utilizing JavaScript

Here is my current code snippet: <script> $(document).ready(function() { $('.scrolls').stop().animate({ scrollLeft : 4000 },100000, 'linear') }) </script> I am looking for a way to halt the animation once ...

Exploring Nashorn's Global Object Variables Through Access and Intercept Techniques

I recently came across a question called "Capturing Nashorn's Global Variables" that got me thinking. I'm facing limitations when it comes to capturing the assignment of variables to the global object. For example, let's say I evaluate the ...

Limit selection choices in select element

Similar Question: Prevent select dropdown from opening in FireFox and Opera In my HTML file, I have a select tag that I want to use to open my own table when clicked. However, the window of the Select tag also opens, which is not desirable. Is there a ...

Are arrays being used in function parameters?

Can the following be achieved (or something similar): function a(foo, bar[x]){ //perform operations here } Appreciate it in advance. ...

Exploring TypeScript to get a ref with the Vue Composition API

The issue I'm facing is related to Vetur underlining 'null' in the following line: const firstRef = ref<HTMLElement>(null) <template> <input id="first" ref="firstRef"> <button type="button&q ...

What is the reason for the immediate application of the set function in a useState hook within asynchronous functions?

While working with multiple set functions of a useState hook, I noticed different behaviors when calling them in sync and async functions. function Test() { console.log('app rendering starts.'); const [a, setA] = useState(1); const [b ...

Deactivate a setInterval function within a Vue.js component

I am facing an issue in my VUE SPA where I have a component running a recursive countdown using setInterval functions. The problem is that the countdown continues running in the background even when I switch to another view, but I want to destroy the setIn ...

Can the width of an offcanvas panel be adjusted?

Currently implementing the offcanvas component in my project, but I'm looking to make the panel wider than the standard size. Specifically, I want it to be 35% width. I've attempted to utilize the panelClass NgbOffcanvasOptions property, however, ...