Communicating Data Between Brother Components in Angular 10

I'm looking for a way to exchange data between two sibling components effectively.

  • Component 1: Component 1 serves as my navigation bar and includes an option to change the language of the app (using ngx-translate). This language selection is presented through a dropdown menu with various options.
  • Component 2: On the other hand, Component 2 functions as a blog featuring multiple posts. These posts are stored in a MySQL database, with each post corresponding to one of two possible languages. The posts are segregated into different tables within the database based on their respective languages.

Our objective here is to trigger an HTTP request to the backend when the language selection changes within Component 1. This request should include the currently selected language so that we can retrieve the relevant posts from the appropriate table in the database.

Does anyone have any insights or suggestions on how to capture the selected language in Component 2 whenever the language dropdown in Component 1 is modified?

Answer №1

If you are utilizing ngx-translate, leverage its service to determine the selected language instead of relying on your component.

@Component({ ... })
export class Component2 implements OnInit {
    constructor(private translate: TranslateService) { }

    ngOnInit() {
        this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
            // execute your code here
        });
    }
}

Explore the documentation of the ngx-translate library for a comprehensive list of events and properties available.

Answer №2

Utilize RxJS in this scenario to create a service containing a BehaviorSubject. Whenever a value is altered in the first component, update the value of this BehaviorSubject. Subsequently, within the second component, monitor any changes to the subject's value and initiate a call to a different language-specific service.

Below is an example of the service logic:

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

@Injectable({
    providedIn: 'root',
})

export class LanguageService {
    private _languageState: BehaviorSubject<Language> = new BehaviorSubject<Language>();

    constructor() {}

    setLanguageState(lang: Language) {
        this._languageState.next(lang);
    }

    onChangedLanguageState() {
       return this._languageState.asObservable();
    }
}

When the language is switched in the first component, simply update the subject using

this.languageService.setLanguageState(lang)
.

In the second component, listen for changes with

this.languageService.onChangedLanguageState.subscribe(() => {// make http request })

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

End the Angular RxJS stopwatch after a specified number of seconds

I am currently enhancing my scoreboard timer component by incorporating a stopwatch feature. The current setup involves modifying the countdown clock that was previously implemented. The stopwatch is designed to run continuously, but I would like to impl ...

Utilizing React across various sections of a traditional website

I have transitioned from using Angular 1.x to React in my server-rendered ASP.NET website built on Umbraco CMS. While I am familiar with creating single-page applications (SPAs) using create-react-app, I now need to incorporate React components in various ...

Issues arise when attempting to use two HTTP get requests in a single AngularJS controller

Having two http GET requests in one controller, causing intermittent issues where only one of the GET requests works or sometimes none of them are shown. Any suggestions? }).controller("nextSidorAdminCtrl", function($scope,$rootScope,$http,$location,$s ...

Typescript loading icon directive

Seeking to create an AngularJS directive in TypeScript that wraps each $http get request with a boolean parameter "isShow" to monitor the request status and dynamically show/hide the HTML element depending on it (without utilizing $scope or $watch). Any ...

Leveraging AJAX for transmitting form information to a php script without relying on jQuery

I want to explore AJAX by implementing a basic form data submission to a php script and database. For educational purposes, I've reached a standstill after hitting the "Create Profile" button with no action. Could someone spot any syntax or structural ...

Is it feasible to run a function immediately following a reload?

Recently, I came across a code snippet that intrigued me: setTimeout(function() { window.location.reload(true); if ($scope.attribute.parentAttribute.id) { angular.element(document.getElementById($scope.attribute.parentAttribute.id)).click(); ...

javascript loop that runs on every second element only

After completing an ajax query, the following JavaScript code is executed. All of my images are named "pic". <script type="text/javascript> function done() { var e = document.getElementsByName("pic"); alert(e.length); for (var i = 0; ...

Create buttons to increase or decrease values using Bootstrap and JavaScript

What is the proper way to make this button function properly? I tested adding this line of javascript code, however it prompts an alert without clicking on the buttons as well. document.querySelector(".btnminus").addEventListener(onclick,ale ...

Tips for verifying the existence of a row with a specific id using jQuery

Is there a way to use jQuery to verify if a table contains a row with a certain id? ...

Troubleshooting: Angular 6 Renderer2 Issue with Generating Dynamic DOM Elements for SELECT-Option

Currently, I am attempting to dynamically create a select option using Renderer2. Unfortunately, I am facing difficulties in creating the <Select></Select> element, but I can confirm that the <options> are being successfully created. Due ...

Error: The module 'cropbox' could not be located. 2

I posed the inquiry Module not found: Error: Can't resolve 'cropbox' Unfortunately, I did not receive a response, prompting me to delve into more specific issues and scour StackOverflow for solutions. After investigating, I identified thr ...

An introduction to utilizing .keypress() in jquery

I'm exploring the use of .keypress() to allow users to press enter and trigger a button click on my modal (which closes the modal). When I initially code it as: $(document).keypress(function () { console.log('keypress'); }); it works, but ...

tips for dynamically highlighting search bar after choosing a different dropdown option - vuejs

I need to filter products in my application based on name and category. To achieve this, I have included a search text box and a dropdown select box. The dropdown select box offers two options: 1. Search products by name 2. Search products by category name ...

Setting up React to dynamically insert data using input fields

Recently, I've dived into the world of ReactJS. Learning it has been quite challenging for me, and I often find myself feeling demotivated while working on it. One particular issue I'm facing is trying to insert data into an h1 element using an ...

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...

Click event handling in JavaScript - Manipulating HTML tables

Currently, I am delving into the world of JavaScript and have been focused on experimenting with Mouse events to gain a deeper understanding of their functionality. <html> <head> <title>Mouse Events Example</title> <scri ...

Tried to enroll the RCTBridgeModule category as RCTFileReaderModule

Trying to register the RCTBridgeModule class RCTFileReaderModule with the name 'FileReaderModule' failed because the name was already taken by the FileReaderModule class. This issue arises when attempting to launch an application on iOS using th ...

Tips for streamlining distinct states and generalized state in UI Router

I've set up the following configuration in my JS app under the $stateProvider section using angular ui-router: .state('login', { url: '/login', templateUrl: 'app/login/login.tmpl.html', controller: &apo ...

How can I stop the serverclick event of an HTML button from being triggered when form validation fails?

I am facing an issue where I need to validate a form before the HTML button's serverclick event fires. However, the client and server events are triggering at the same time. HTML <button runat="server" id="imgLogin" type="submit" class="btn" styl ...

Unlocking the potential of Three.js with mouse picking

I am looking to implement object picking in the following code snippet: var Three = new function () { this.scene = new THREE.Scene() this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000) this.camera.po ...