Obtaining a value from HTML and passing it to another component in Angular

I am facing an issue where I am trying to send a value from a web service to another component. The problem is that the value appears empty in the other component, even though I can see that the value is present when I use console.log() in the current component.

AppComponent

ts

level: string = '';

getCustomer(id: string) {
    this.isLoading = true;

        this.customerService.getOne(id)
            .subscribe(
                (data) => {
                    this.level = data.level;
                    console.log(this.level); // The value is visible here
                },
                (error) => {
                    this.errorMessage = error;
                },
            );
      }

html

    <div class="col-lg-8">
      <app-other-component [active]="level"></app-other-component> 
    </div>

AppOtherComponent

ts

@Input() active: string;

ngOnInit() {
    console.log(this.active); // The output is an empty string here
  }

It seems like the line

<app-other-component [active]="level"></app-other-component>
is executing before the value of 'level' is actually filled. How can I resolve this issue? Thank you.

Answer №1

To ensure that the app-other-component is only visible after the value is set from the web service, you can wrap the div in an *ngIf:

<div class="col-lg-8" *ngIf="level">
  <app-other-component [active]="level"></app-other-component> 
</div>

As Yousef mentioned, you will receive the updated value of @Input in the ngOnChanges method rather than in the ngOnInit method. The ngOnChanges method is called whenever the value of an @Input property changes:

@Input() active: string;

ngOnChanges() {
  console.log(this.active); // This is where you will see the updated `active` string value.
}

Answer №2

It seems the issue lies with the 'this' pointer in the callback function, as it does not refer to the component. To solve this, consider changing it to 'self' as shown below:

let self = this;
this.customerService.getOne
...
(data) => { self.level = data.level; }

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

Showing the Enum name rather than the value in an Angular HTML template for a bound Typescript Interface

After retrieving an array of objects with various properties from a .NET Controller, I am utilizing the following Typescript code: import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Co ...

Unable to find solutions for all parameters in AngularFirestoreDocument: (?, ?)

I have integrated Angular 11 with Firebase for authentication and Firestore for data collection. However, I encountered an error message Can't resolve all parameters for AngularFirestoreDocument: (?, ?). How can I resolve this null injector issue? On ...

JavaScript filename

This question may appear simple, but I believe the answer is not as straightforward. Here it goes: Should I keep the filename of jQuery as "jquery-1.3.2.min.js" for compatibility reasons, or should I rename it to jquery.js? In my opinion, it's best ...

A guide on how to perform a PUT or DELETE operation for Azure Table Storage using Node.js

I've been faced with a challenge in my project where I aim to create basic CRUD functionality for Azure Table Storage. However, I'm encountering difficulties in generating a valid SharedKeyLite signature. While I can successfully generate valid ...

Dim the background for all elements except for one

Seeking a way to create a dimmed-background effect by adjusting the opacity of all elements on the page except for one specific element. I've experimented with using the :not() selector as well as jQuery selectors to exclude certain elements, but have ...

To activate two separate click events, one for an absolute element and another for the element positioned behind it, simply click on the desired absolute element to trigger both actions

Is it possible to trigger click events for both of these elements? position: relative container ELEMENT 1: standard div ELEMENT 2: position: absolute div In real life, element 2 is a transparent backdrop designed to capture clicks on top of the header ...

"Users have reported that the Express body-parser feature sometimes results in req.body returning

I have developed a basic Express server that utilizes the body-parser module to access POST parameters. Here is how my application is structured: /index.js: 'use strict'; const express = require('express'); const app = express(); con ...

Ensuring Jquery validation is triggered before submitting a form to PHP

I have been struggling with a particular issue and decided to seek help. I have a form filled with user data that I have successfully validated using js/jQuery before sending it to php for processing. Here is how I am achieving this: form.submit(functio ...

Transmit the Boolean value to the controller using ajax requests in asp.net.core with C# programming

Within the view section, there is a form that includes a checkbox input. <div class="checkbox"> <label class="">active</label> <div class="icheckbox_flat-green checked" style="position: relative;"> <input type="checkbox" id="A ...

Uncovering the Android tablet browser: A guide

I have implemented the code below to detect mobile/tablet browsers. function isMobile() { var index = navigator.appVersion.indexOf("Mobile"); return (index > -1); } Although it works well for desktop browsers and iOS devices (iPhon ...

Is Redux or Flux the default state management tool used in React?

After using npx create-react-app my-app --template typescript to create a new React app, what is the default software architecture (MVC, Redux, or Flux)? I've been researching the differences between them and it has left me feeling a bit confused. I w ...

How can a React app be developed offline?

I am currently working offline with no access to the internet. Node.js is already installed on my system, but I encountered an error when trying to run the command npm create-react-app. Is there a way for me to execute npm commands and set up a react app ...

The art of controlling iframe elements with jquery

I've been researching various topics related to this issue, but I'm still unable to achieve the desired outcome. Currently, I am embedding an iframe within an HTML document like so: <iframe class="full-screen-preview__frame" id="nitseditpre ...

What are the steps to lift non-React statics using TypeScript and styled-components?

In my code, I have defined three static properties (Header, Body, and Footer) for a Dialog component. However, when I wrap the Dialog component in styled-components, TypeScript throws an error. The error message states: Property 'Header' does no ...

Sorting objects in an array according to their prices: A guide

Suppose we have the following data structure: var lowestPricesCars = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", ...

Developing a custom data structure that identifies the keys of an object with a designated nested attribute

There is an intriguing scenario where dynamically defining types from a centralized JSON data store would prove extremely beneficial. Allow me to elaborate. The JSON file I possess contains a roster of various brands. // brands.json { "Airbus": { ...

This object does not have support for the attribute or method "getAttribute"

I've searched for solutions, but nothing seems to work for me and now I'm feeling quite lost. My current setup involves Cordova, Ionic, and Angular 2. Below is the HTML snippet: <ion-col *ngFor="let value of myButtonsFirstRow" width-25> ...

In React, the Textarea component that displays the character count only updates its value after a page reload

Contained within this element is the following component: import React, { useEffect, useState } from 'react'; import { TextareaTestIds } from '../utils/test-ids'; export interface TexareaProps extends React.TextareaHTMLAttributes<H ...

Trouble with Click event not working in Electron and mouse cursor not changing when hovering over an HTML button?

I'm in the midst of a project that involves using the electron framework. Within my project, I have an HTML file, a CSS file, and a Javascript file. The issue at hand is that when I hover over a button, the expected hand pointer icon fails to appear d ...

``There seems to be an issue with the functionality of Passport.js' multiple login system

I'm encountering a strange issue with my login system. Everything seems to be working fine, including local login, Google login, and Facebook login. However, the problem arises when I attempt to register with Google after already registering with Face ...