loading dynamic content into an appended div in HTML using Angular

Here is the HTML code from my app.component.html file:

<button mat-raised-button color="primary" 
    mat-button class="nextButton" 
    (click)="calculatePremium()">
  Calculate
</button>


<div id="calculatedData">
                                
</div>

The button above triggers a calculation using an API call. While I am able to get the expected output, the dynamic value generated after clicking the button does not display inside the specified div as intended. Instead, it shows up as undefined in the browser.

Below is a snippet of my app.component.ts file showcasing the calculation process:

calculatePremium(){
    console.log("calculating");
    let frmData: any = this.form.value;
    this.dobVal = frmData.contact.dob;
    let onlyYear = String(this.dobVal).split(' ')[3];
     
    // AGE    
    let age = (Number(new Date().getFullYear()) - Number(onlyYear));
        

    // NAME
    let name = frmData.contact.firstName;    
    

    // GENDER    
    let gender = frmData.contact.gender;    


    // smoking    
    let smoker = frmData.basicInfo.isSmoker;    


    // no of dependents    
    let dependentsCount = Number(frmData.basicInfo.adults) + Number(frmData.basicInfo.children);    
    

    let finalObj = {
        'name': name,      
        'age': age,      
        'gender': gender,      
        'smoking': smoker,      
        'dependent': dependentsCount
      }    

    this.calcualte.calculatePremium(finalObj).subscribe(
      (data: any) => {
        //success        
        console.log(data);        
        Swal.fire('Plan Amount', 'is  ' + data.name + data.amount, 'success');        
        this.amount = data.amount;        
        console.log(this.amount);        
        
        //alert('success');     
      },      
      (error) => {        
        //error        
        console.log(error);      
      });    
      console.log(this.amount);        
      const x = document.getElementById('calculatedData');  
This is where the dynamic value should be displayed, but currently appears as undefined on the browser:
x.innerHTML = `<div class="appendme">${this.amount}</div>`;    
const len = x.getElementsByTagName('div').length;    
console.log(len);  
}}

Answer №1

New to Angular? Make sure to take a look at their quick tutorial for beginners. It covers all the fundamental concepts.

If you're dealing with a situation where you need to confirm whether the variable amount is set, use *ngIf along with interpolation to display its value.

<div *ngIf="!!amount">
  {{ amount }}                                    
</div>

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

What steps can be taken to ensure that any new elements generated by JavaScript do not disappear upon refreshing the page

I am currently working on a project where I am creating a list by collecting user information and storing it in a MySQL database. When the user clicks the 'add' button, a new element is added to the bottom of the existing list which is coded in H ...

Angular's observables were unable to be subscribed to in either the constructor or ngOnInit() functions

Currently, I am incorporating an observable concept into my application. In this setup, a service is called by component1 to emit an event that is then subscribed to by component 2. Below is the code snippet for reference: Service Code export class Mes ...

Altering the hue of a picture

Looking to alter the color of an image on a webpage, specifically a carport. It's crucial that the texture and shadows remain consistent. Swapping out images with different colors would require an excessive amount of images, so I'm seeking advice ...

Tips for showcasing content by hovering over buttons with the help of Bootstrap3 and Jquery

My code and fiddle are currently set up to display buttons when hovered over, but I want to modify it so that only the relevant button is displayed when a specific text is hovered over. For example, if "Water" is hovered over, only the button for Water sho ...

Node.js - Error: JSON.Parse and JSON.Stringify are not recognized as functions

Is it possible to convert a string to JSON and vice versa without any additional npm packages? I am currently using JSON.Stringfy in my router.js file. Are there any specific npm modules that need to be added to the project in order to use the JSON.Stringf ...

What is the best way to augment an AJAX array response with additional data?

I'm working on an AJAX request and I need to add additional properties to the response I receive. Can anyone offer some guidance? Here is the AJAX request code I'm using: var form_data = {}; $.ajax({ type: "GET", url: "../../../sample_ ...

How to dynamically inject HTML content from a child component into a different component using Angular 5

Is it possible to customize the content of a reusable header section based on the current route data in Angular? The header currently displays a title and description pulled from the route data property. My concern is how to dynamically inject different H ...

Is the treatment of __proto__ different in the fetch API compared to manual assignment?

When using fetch to retrieve a payload containing a __proto__, it seems that the Object prototype is not affected in the same way as when directly assigning to an object. This behavior is beneficial as it ensures that the Object prototype remains unaffect ...

Can you explain the contrast between uploading files with FileReader versus FormData?

When it comes to uploading files using Ajax (XHR2), there are two different approaches available. The first method involves reading the file content as an array buffer or a binary string and then streaming it using the XHR send method, like demonstrated he ...

Pause the counter based on the data attribute containing multiple values

I have a collection of div elements, each with a unique data-attribute value. My goal is to display these values in the divs using JavaScript by incrementing a counter. const numbers = document.querySelectorAll(".number"); console.log(numbers); let c ...

"What is the best way to change the props of a React component that has already been rendered from App.js

My React component, MoviesGallery.js, is set up with the following structure: class MoviesGallery extends Component { constructor(props) { super(props) this.state = { currentImage: 0 }; this.closeLightbox = this.closeLightbox. ...

Retrieve a specific line of code from a snippet of JavaScript

I am looking to extract a specific line of code from a script that I am receiving via ajax... The line in question is new Date(2010, 10 - 1, 31, 23, 59, 59) found within the following snippet: jQuery(function () { jQuery('#dealCountdown').count ...

Issues with Node.js routes on the express server aren't functioning as expected

I used to have a node.js express server up and running on my previous server. However, after migrating to a new server, the code seems to have stopped functioning. Let me share the setup of my server: var fs = require('fs'); var express = requi ...

Integrating CSS with Material-UI in a React project: A step-by-step guide

I am currently developing a project using React (along with TypeScript) and the Material-UI library. One of my requirements is to implement an animated submit button, while replacing the default one provided by the library. After some research, I came acr ...

I'm looking to integrate Jest in my React project with npm. How can I achieve

I've developed my application with create react app and npm. While reviewing the official documentation for jest at https://jestjs.io/docs/tutorial-react, I noticed that they only provide information on testing CRA apps using yarn. Does this suggest t ...

Create a new instance of the parent class in TypeScript to achieve class inheritance

Looking for a solution to extending a base class Collection in JavaScript/TypeScript to handle domain-specific use cases by implementing a "destructing" method like filter that returns a new instance with filtered elements. In PHP, you can achieve this usi ...

Utilizing React to implement a search functionality with pagination and Material UI styling for

My current project involves retrieving a list of data and searching for a title name from a series of todos Here is the prototype I have developed: https://codesandbox.io/s/silly-firefly-7oe25 In the demo, you can observe two working cases in App.js & ...

Angular 11 Import Guide for MAT_DATE_LOCALE

I am struggling with importing 'mat-date-locale' in Angular 11 modules. The link I followed didn't provide a solution, as mentioned here: Cannot find name "MAT_DATE_LOCALE" with Material.angular Datepicker. In my project, I have A ...

Storing information when an object is indexed in a for loop, to be retrieved later when

My JavaScript code includes an AJAX call that takes user input from a form and uses it to search for a JSON object. The matching objects are then displayed in a datalist successfully. Everything is working well so far, but now I want to extract specific f ...

Issue encountered during creation of a polyline in Cesium

When attempting to create a polyline in my ReactJs app using the code below, I encountered an error message stating "DeveloperError: Expected value to be greater than or equal to 0.0125, the actual value was 0." Can someone shed some light on why this er ...