Syncing Views with Callback Variables in Angular 2

Within my angular2 project, I am utilizing FileReader to read a csv file. Once the onloadend callback is triggered, a variable holds the content of the csv file.

Below is a snippet from my component.ts :

items: Array<any> = []

...

readCSV (event) {
   let csvFileParseLog = this.csvFileParseLog;
   r.onloadend = function(loadedEvt) {
       devicesFile = files[0];
       let csvFileParseLog = [];
       parseDevicesCsvFile(contents) // A function returning an observable
           .subscribe(newItems=> {
               csvFileParseLog.push(newItems); // Result stored in csvFileParseLog
           },
           exception => { ... }
       );
  };
}

I have attempted to bindcsvFileParseLog to my view by passing the value into items, but have not been successful.

Here's how it's represented in my componenet.html :

<div *ngFor="let c of csvFileParseLog">
    {{ c.value }}
</div>

Could someone provide guidance on how to display this content within my view component and iterate over it using ngFor?

Answer №1

When setting up the event listener, make sure to use arrow function syntax like this:

It should look like this:

r.onloadend = (loadedEvt) => {

Using this arrow function ensures that `this` will work correctly within that function.

Simply add this line of code:

this.csvFileParseLog.push(newItems);

You can remove this line:

let csvFileParseLog = this.csvFileParseLog;

If needed, inject the ChangeDetectorRef in the constructor like so:

constructor(private cdRef:ChangeDetectorRef) {}

Then call it in the subscribe method like this:

.subscribe(newItems=> {
    this.csvFileParseLog.push(newItems); 
    this.cdRef.detectChanges();
},

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

When attempting to host a web application built using the Impact JavaScript game engine on a local server, Chrome throws CORS errors

Currently, I am working on a webapp created with the Impact JS game engine that needs to run locally without using a localhost (using file:///C:/...). The issue I am facing is with Chrome, as it is blocking the loading of images (mainly png/jpg) from the m ...

Eliminate Tracking Parameters from URL

I rely on UTM parameters to monitor incoming links within Google Analytics. Consider a scenario where my URL appears as follows https://www.example.com/store?utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale I am looking to streaml ...

A Guide to Displaying HTTP Error Messages on the Angular Login Page

When encountering a form validation failure on my login page, I utilize ngMessage to display an error message. However, I now want this div to be displayed in the event of an HTTP 500 error. While I can retrieve the corresponding error message when an HTTP ...

Navigate to a new tab with a parameter in AngularJS

Is there a way to open a new tab using state.go with parameters? This is the state configuration: .state("view", { url: "/view", templateUrl: 'app/components/view/view.html', controller: 'viewController', params: { ...

Performing an Ajax request in Django without the use of a form

Being new to Ajax, I am currently trying to understand how it works. Specifically, I am attempting to make an Ajax call by linking my Javascript event handler to the onclick function of a span element. There is no form element in my template, so I am wonde ...

Refreshing specific iframes without having to reload the entire webpage using jQuery

As the page loads initially, a hidden iframe and other visible ones are present. When a button is clicked, one of the visible iframes needs to be hidden while another becomes visible (with its src attribute set accordingly). The goal is to achieve this wit ...

Ways to access information from an Angular model within a controller

hydrate.component.ts import { Component } from 'angular/core'; import { userDataService } from 'some/different/path'; @Component({ selector: 'hydrate', templateUrl: './hydrate.component.html' ...

Major mistake encountered while attempting to establish Github pages

Attempting to configure my project on GitHub pages, but encountering an error while following the steps outlined in the documentation. I am at Step 2 and facing image-related issues. Any suggestions? Operating on Windows 7 with NPM 5.6.0 and Node 8.11.3. ...

Picture fails to load on Ionic app on the device

Currently, I am utilizing Ionic 3 for my project. The location of the images file is \src\assets\img. This pertains to a basic page implementation. export class BasicPage { items = []; constructor(public nav: NavController ,private adm ...

Separate the JSON array according to the type of suggestion it's being given

My JSON array is structured like this: [ { "characterID": 0, "description": "Series 1", "id": 1, "seriesID": 0, "status": "ACCEPTED", "type": "SE ...

Steps to adding a collection of links (stylesheets, javascript files) to each html document

Is it feasible to add a list of links to multiple HTML files? I was inspired by W3 School's W3 Include functionality, which allows you to import blocks of HTML code into various files simultaneously, making it convenient for making changes across many ...

Issues with triggering the success block in AngularJS and Node.js Express when using $http.get

As a beginner in the world of AngularJS and Node.js, I'm facing an issue with my $http.get method. The problem is that the success callback block does not get executed when the request is successful, whereas the error callback works just fine when the ...

Issue with JSON parsing on non-Chrome web browsers

Encountering a problem with parsing fetched JSON data from browsers other than Chrome, Firefox providing error message: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data". Notably, code functions in local node.js environmen ...

Customize validation timing in Angular Reactive Forms

One common query about the conditional validator is understanding when exactly it gets triggered. Imagine a simple form with just two fields this.form = formBuilder.group({ emailRequired: [false], emailRecipients: [''] }); Now, let's s ...

Implementing Authorization Headers in Angular for Secure HTTP Post Requests

I have been struggling to add Authorization Headers to a Post request after extensive research and trying various ways of adding headers to the request. I need to authenticate the post request of my Angular app to a Django server. headers2 = { "Conte ...

Tips for avoiding duplicate Dialog openings in Angular Material with Angular 5

<mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let person of filteredPersons | async" [value]="person.name" (onSelectionChange)="selectedPersonsInDialog(person)"> <img style="vertical-align:middle;" ari ...

What is the process for importing string data into an Excel document using Angular?

I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file? To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunk ...

VueJs Ellipsis Filter: Enhance Your Texts with

Using Vue.JS, I am dynamically injecting text content into a DOM element. <article>{{ movie.summary }}</article> My goal is to implement an auto-ellipsis filter. Essentially, the code would look like this: <article>{{ movie.summary | e ...

The implementation of CommonJS modules allows for efficient modularization

While using Nx for my Angular workspace, I noticed something that sparked a question in my mind. Why is it necessary to use CommonJS modules in all tsconfig.spec.json files for libs? Looking at Nx examples, I observed that not all libs include it, only app ...

Receiving an alert in VSCode regarding the usage of CharAt function in conjunction with Vuejs

While attempting to extract the first character of a computed property, I utilized the charAt() function. Despite the fact that it is functioning correctly, I am receiving a warning from VSCode indicating that it is not the correct usage. computed: { ...m ...