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

Make sure a specific piece of code gets evaluated in a timely manner

To ensure the default timezone is set for all moment calls in the app's lifetime, I initially placed the setter in the entry point file. However, it turns out that this file is not the first to be evaluated. An issue arose with one of my reducers wher ...

Ways to include additional parameters in jQuery ajax success and error callbacks

When working with a jQuery AJAX success/error function similar to the following: success: function (data, textStatus, jqXHR) { } error: function (jqxr, errorCode, errorThrown) { } I am wondering if there is a method where I can pass an array of valu ...

trigger a function when the iframe is altered

I am currently working on creating a function that can process credit card payments using an iframe. The challenge I am facing at the moment is dealing with error messages appearing in a less than ideal manner. Photo: I have been attempting to capture the ...

What is the best way to upload an image BUFFER to a website using puppeteer?

What I have learned to do: Save an image file from a source like imgur as a buffer and download it to disk Display an image on a page by uploading it from disk using elementHandle.uploadFile(path) However, this method only works locally on my machine. My ...

Using the Angular 4 filter pipe in conjunction with server-side pagination functionality

When using filter with pagination, the issue arises where searching for a Name filters the results but the pagination remains static. This means that if the search returns 3 filtered records, the pagination will still display multiple pages for navigation. ...

The premature firing of the fireContentLoadedEvent in Internet Explorer is causing issues

I've encountered a strange issue with IE8 recently. My code has been functioning properly for a while and still works perfectly in Firefox, but all of a sudden Prototype has stopped calling my event listeners for dom:loaded. I typically attach them u ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

A guide on displaying data in a table using a select dropdown in a pug file and passing it to another pug file

After creating a single page featuring a select dropdown containing various book titles from a JSON file, I encountered an issue. Upon selecting a book and clicking submit (similar to this image), the intention was for it to redirect to another page named ...

How to effortlessly convert a JSON string into a JavaScript object

Hello everyone, I am working with DynamoDB and need to parse the JSON Object that is returned from a call in order to retrieve the password hash field. jsonString = JSON.stringify(data) console.log(jsonString) This is what the output looks like: {"Count ...

Placing two texts alongside a logo in a Bootstrap Navbar: Step-by-step guide

As I venture into the world of Bootstrap, I am on a quest to create a Navbar Component similar to this design: https://i.stack.imgur.com/NidKQ.png I attempted to use the Navbar Image and Text code, but encountered an issue where the text would only displ ...

Issue with TypeScript retrieving value from an array

Within my component.ts class, I have defined an interface called Country: export interface Country{ id: String; name: String; checked: false; } const country: Country[] = [ { id: 'India', name: 'India', checked: false}, { ...

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

How can you resolve redefinition warnings detected by the CSS Validator?

After running my site through the W3C CSS Validator, I was surprised to see that it returned a total of 3146 warnings. The majority of these warnings are redefinition alerts, such as: .fa.fa-check Redefinition of color .fa.fa-check Redefinition of ...

What is the best method for storing a JavaScript widget with analytics - should it be done dynamically or statically?

My widget comes with a customizable boot loader that is used on websites. The boot loader file retrieves the settings for the widget and generates it accordingly. Normally, the content of the bootloader file remains static unless there are modifications ma ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

Click on the div in Ionic 2 to send a variable

<div class="copkutusu" (click)="kanalsil(kanalid,deneme)" #kanalid id={{ver.channelid}} #deneme id={{ver.channelapikey}}></div> I am requesting kanalid.id and deneme.id in my .ts file. Even though they are the same variable names, they repres ...

Tips for dynamically populating a mat-table dataSource

While working with backend data streaming, I encountered an issue where trying to push an event to dataSource resulted in an error stating that dataSource is not defined. Can anyone provide guidance on how to dynamically add data to a materialize table? s ...

Positioning my login form in the right spot is proving to be a challenge

I'm working on integrating this form into my website, but I'm having trouble placing it in the top right corner of the header. Below is the HTML code: $(function(){ var $form_inputs = $('form input'); var $rainbow_and_b ...

Can you merge multiple req.body requests?

I am exploring a scenario where I have a list of items that need to be iterated through, with each item having the value of i added to it to retrieve the next set of information. For example: By concatenating the string "req.body.item" + i + "Title", you ...

Is there a way to display the JavaScript widget exclusively on the homepage or main page

How can I limit the display of a Twitter widget on my blog page to only show on the main page and hide it when visitors navigate to sub-pages or individual blog entries? ...