Send the data value to the header section

Is there a way to dynamically display the project number within the header component, which is visible on all pages?

Here is the code for the Header component:

<div class="d-flex flex-column flex-md-row align-items-center px-md-4  bg-brown text-white ">

<h2 class="my-0 mr-md-auto">
<span>Project {{numero}}</span></h2>

<nav class="my-2 my-md-0 mr-md-3">
    <a class="p-2 text-white" href="#">Projects</a>
    <a class="p-2 text-white" href="#">Exit</a>
</nav>

</div>

And here's how it's included in other components' HTML files:

<app-header></app-header>
<div>my component</div>

In the corresponding typescript file (.ts), the 'numero' variable is defined as follows:

numero: string = "MY NUMERO";

Now the question arises: How can we pass and update the 'number' value in the header from other components? Should we utilize @Input () decorator for this purpose?

Your valuable insights are greatly appreciated. Thank you.

Answer №1

If you're looking for a suggestion, I would advise utilizing a Service

  • To begin with, declare the Service
export class NumeroService {
    numeroSubject$ = new BehaviorSubject("MY NUMERO")
    numero$: Observable<string> = this.numeroSubject$.asObservable();
    updateNumero(newNumero: string) {
      this.numeroSubject$.next(newNumero)
    }
}

The code snippet above creates a BehaviorSubject with the initial value of "MY NUMERO". This creates an Observable with the same value. To update this value, simply pass the new value to the next() function of the Subject

  • Next step is to inject this service in the HeaderComponent TypeScript
constructor (private numeroService: NumeroService) {}
  numero$ = this.numeroService.numero$

HTML

<span>Project {{numero$ | async}}</span>

We utilize the async pipe to subscribe to the Observable

  • Lastly, inject the service where you want to update the numero$
constructor (private numeroService: NumeroService) {}
  ngOnInit() {
    this.numeroService.updateNumero("NEW NUMERO")
  }

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

Using dual index variables in Angular 4's ngFor loop for iterating through arrays

Is there a way to generate unique index numbers for items printed only on Saturdays? Specifically, I want the index to start from 0 once Saturday begins and continue incrementing. The rest of the options should have the same index numbers. Any suggestions ...

Creating a mechanism for automatic refreshing of JWT tokens in a Spring Boot and Angular application

I am working with Spring Boot and storing JWT tokens in httpOnly cookies. How can I implement automatic token refresh using the existing refresh tokens method on the backend? ...

Having trouble with Angular and PrimeNG: CSS styling not rendering

I recently started using PrimeNG but I'm having trouble getting the styles to look good. Despite not seeing any errors in ng serve or the browser logs, the components (a calendar and 3 buttons) appear dull. app.module.ts import { BrowserModule } fro ...

Why is the quantity of my item being increased? My method is adding it when it shouldn't be

I have a project in Angular that involves an online store. However, every time I click the button "agregar a carrito" (add to cart in Spanish), my item's quantity seems to increase inexplicably. ts. removeItem(item: iProduct) { if (item.quantity ...

Angular Object

I am currently working on a small Angular project that focuses on displaying and managing bank accounts using CRUD operations, including transactions. However, I have encountered an issue that is puzzling me. Whenever I click on one of the listed accounts, ...

Generate a unique identifier based on data type

Is it feasible to create a function signature based on type in this manner? I have successfully created a function signature as shown below. type Data = { update: boolean }; type Distribution<T> = { on: <K extends keyof T>(key: K, list ...

What causes the index to display [object Object] rather than an integer in React?

It has been a long time since I last worked with React, and now I'm facing an issue. Whenever I use console.log to display the index within the map function, my console output looks like this: https://i.stack.imgur.com/VbGmE.png However, the result ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

Arrangement of Bootstrap card components

Each card contains dynamic content fetched from the backend. <div *ngFor="let cardData of dataArray"> <div class="card-header"> <div [innerHtml]="cardData.headerContent"></div> </div> <d ...

When executing prisma generate, an error of TypeError is thrown stating that the collection is

While using typescript with Prisma, I encountered an issue when trying to run prisma generate, as it kept throwing the following error: TypeError: collection is not iterable. at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21) at ...

Troubleshooting issue: Webpack dev server's Hot Module Replacement not functioning correctly when

I've been working on a Vue 2 application that is mostly JavaScript, and now I am looking to incorporate some new TypeScript modules and components into it. Everything runs smoothly when I start the webpack dev server. However, whenever I make a chang ...

Using Typescript and React to assign an array object to state

Here is the situation: const [state, setState] = useState({ menuCatalog: true, menuCommon: true, fetched_data: [] }); An example of data I am trying to set to the state property "fetched_data" looks like this: [{"id": 1, "name": "some_name", " ...

How can interfaces be effectively integrated with node and mongoose?

I am working on a model interface where I need to fetch specific data from the record // file: code.interface.ts import { Document } from 'mongoose'; export interface CodeI extends Document { readonly _id: string; readonly logs: any; } Howe ...

Issue encountered while attempting to initiate a new project with Angular CLI

Encountering an error while trying to create a new app using Angular CLI Attempted solutions: npm cache clean --force npm cache verify Unfortunately, the above steps did not resolve the issue Please refer to the image linked below https://i.sstatic.ne ...

Issue with Master Toggle functionality for checkbox within expanded rows of Mat-Table does not function correctly

I'm facing an issue with my multi-row expandable mat table grid where the master toggle for inner grid checkboxes is not working. Each row fetches data from different APIs on click, and I have a checkbox selection in every row for the inner grid. Int ...

Leverage CSS variables to dynamically create class names within SCSS

Can CSS variables be used to generate class names? I am incorporating SCSS in an Angular project and I am looking to base my class names on the @input color component property. I have stored the input in a CSS variable called --color-variable to utiliz ...

Determine the consistent type for numerous properties

Is it feasible to have Typescript automatically infer the type of multiple properties to be the same, or even infer the types based on a specific property? For example, consider the following code snippet -> interface Test<T> { value1: T; val ...

Leveraging Enums in Angular 8 HTML template for conditional rendering with *ngIf

Is there a way to implement Enums in an Angular 8 template? component.ts import { Component } from '@angular/core'; import { SomeEnum } from './global'; @Component({ selector: 'my-app', templateUrl: './app.componen ...

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...

Http Angular service lacks a provider

@Injectable() export class MyService { constructor(private http: Http, @Inject('name') @Optional() public name?: string) { } When setting up my appModule, I attempted to define a provider for MyService service. MyService, import ...