Exploring ways to retrieve and manipulate variables from different components in Angular

Currently working on an Angular app using TypeScript:

The app.component features a top navigation bar, followed by the router-outlet for other components

<navigation></navigation>
<router-outlet></router-outlet>

Navigation Section

@Component({
  selector: 'navigation',
  directives: [ROUTER_DIRECTIVES],
  template: `{{ HERE SHOULD BE USERNAME }}    <a [routerLink]="['Home']">Home</a> | <a [routerLink]="['Logout']">Logout</a>`
})
export class NavigationComponent {}

Login Form (loaded within the router-outlet)

@Component({
    selector: 'login-component',
    templateUrl: 'app/components/login/login.html',
})
export class LoginComponent {

  username ;

  constructor(public router: Router, public http: Http) {
  }
...
}

The purpose of the login.component is to handle user logins. Once a user has logged in, I want to display their username in the Navigation.component. Is there a way to pass the User-Name from login.component to Navigation.component? Alternatively, is it possible to access the variable username within the login.component from the Navigation.component?

Answer №1

Utilize a shared service for both components and save the username within that service.

The login module will save the username in the shared service:

userService.setUser(theUser);

The navigation module allows retrieval of the user from the shared service:

getUser() {
    return userService.getUser();
}

The navigation module's view displays the user by calling

{{ getUser() }}

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

Tips for parsing a string object in JSON without a preceding double quote

I'm working with an array in my Angular application, for example: searchTerm : any[] In the context of a textbox value like {'state':'tn'}, I'd like to push this to the searchTerm array. Currently, I achieve this by adding t ...

Creating Custom Form Control with Custom Validation in Angular 6

I designed the app-input component for displaying an input textbox. I am struggling to implement custom form validation. Can you offer any suggestions? ...

"Encountering issues with running a MongoDB aggregate query involving date fields

I have been attempting to retrieve data from MongoDB using an aggregate query in Node.js for a specific date range. let date = '20230925' let year = date.slice(0, 4); let month = String(date.slice(4, 6)).padStart(2, '0'); ...

What is the best way to retrieve property names that are not nullable from a type?

I am seeking to create a custom mapped conditional type in TypeScript that will allow me to extract property names from a type, while accounting for properties that can potentially have a value of null. For example: interface Person { name: string a ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

Is there a specific method for conducting a production build using AngularCLI rc.1?

Just recently upgraded to angular-cli version 1.0.0-rc1 by following the guidelines provided on the wiki. The application functions properly when I execute ng serve. Similarly, the app works as expected when I run ng build. However, encountering an issu ...

Issue occurred when trying to load controllers during the migration process from AngularJS1 to Angular6

Currently, I am in the process of upgrading AngularJS1 components to Angular6. My strategy involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and storing them under the folder "directive-wrappers". However, wh ...

How to format dates when exporting Excel from Kendo Grid in Angular 2

When attempting to export data from the Kendo UI Grid for Angular, there seems to be an issue with formatting the date column. The actual date value is not being displayed correctly in the exported file. Below is a snippet of the code: <kendo-excelexpo ...

Peeling off the layers of an array declared as const to reveal its mutable version without being restricted to tuples

I'm facing a challenge with an array declared as as const: // example of a simple mock class class Child { _ = "" } const child = new Child(); const schema = [[child], child] as const; // readonly [readonly [Child], Child]; This array rep ...

What is the best way to transfer props between components using typescript?

I have a unique button component that I need to include in another component. The button type and interface I am using are as follows: type IButton = { className?: string, onClick?: MouseEventHandler; children: React.ReactNode; props: IButt ...

Dealing with Placeholder Problems in Angular 2 Material when Using setValue

Encountering an issue with Angular2's material components when a component is updated via setValue. Check out the plnkr link below for more details... [unique PLNKR link] Observed that both the value and the placeholder are occupying the same space. ...

Encountering an unexpected token error while building an Angular4 --prod project that involves Three

Encountering an error while trying to build an Angular4 project in production with the following command: node --max_old_space_size=8192 'node_modules/@angular/cli/bin/ng' build --prod --output-hashing=al Error: ERROR in vendor.422622daea37e ...

Set the default page for the p-table

My English proficiency is lacking. I am currently using a p-table with pagination, but I need to modify the pagination in the HTML code. <p-table #dt [columns]="cols" [value]="values" [paginator]="true" [rows]="10" (onFilter)="filtra ...

receiving list items in JSON format rather than XML or Atom

Upon typing the link of a list in my browser, I am able to view all the data in xml/atom format. The screenshot can be found below: https://i.sstatic.net/9jUKV.png In my search for converting this incoming response to JSON, I utilized the "RequestOptionsA ...

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

A guide on retrieving the values of all child elements within an HTML element using Puppeteer

I have been exploring the capabilities of puppeteer and am trying to extract the values from the column names of a table. <tbody> <tr class="GridHeader" align="center" style="background-color:Black;"> <td cl ...

Angular: Reveal or conceal targeted rows on click interaction

I have a scenario where I am displaying data in a table with multiple rows. Each row has its own set of data and a button that triggers a function when clicked. <table> <th>Col-1</th> <th>Col-2</th> <th>< ...

Problem encountered when trying to deploy a Next.js application with React Hook Form v7 on Vercel platform

I am currently in the process of creating a web application using nextjs and chakra UI while incorporating typescript. I've integrated react hook form for form validation, however I encountered a problem when deploying it on vercel. Check out the scre ...

Utilizing history in React with Typescript: A step-by-step guide

I am currently working on a function that navigates to My Page upon clicking a button. However, I encountered an error when trying to implement it in Typescript instead of JavaScript. I am seeking assistance to resolve this issue. //Topbar.tsx function Top ...

Displaying a portion of the chart's key in a Highcharts BarChart

I need assistance displaying a partial legend (such as min, medium, max) for the X and Y axes, along with a horizontal dashed line at the medium point of the Y axis in a HighCharts BarChart. The graph is compact on the screen, serving as a summary of multi ...