Angular 4: activating a function from a template

In my Angular 4 project, I am trying to calculate the average of some numbers. Here is a simplified version of my component:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent {
  students:string[];
  constructor(private studentsService: StudentsService) {}
  ngOnInit() {
    this.studentsService.getStudents().subscribe(students => {
      ...
    })
    function calculateAverage(arr) {
      var i,
          len=arr.length,
          average=0;
      for (i=0;i<len;i++) {
         average += arr[i];
      }
      return (average/arr.length);
    }
  }
}

The template in my HTML file looks like this (GPARecord is an array of floats):

<tr *ngFor="let student of students">
  ...
  <td>{{ calculateAverage(student.GPARecord) }}</td>
</tr>

However, I am encountering an error in the console:

ERROR TypeError: _co.calculateAverage is not a function

I would appreciate any help in resolving this issue. Thank you!

Answer №1

(i)To utilize TypeScript, you can use let instead of var, and the keyword function is not mandatory.

(ii)It is recommended to move the code outside of the ngOnInit() method.

  calculateAverage (arr) {
          let i,
          len=arr.length,
          average=0,
          obj={};
      for (i=0;i<len;i++) {
         average += arr[i];
      }
      return (average/arr.length);
    }

Answer №2

Your function has been defined within the ngOnInit() method. You should remove the function keyword and move the function outside of this method like so:

export class HomeComponent {
  students:string[];
  constructor(private studentsService: StudentsService) {}
  ngOnInit() {
    this.studentsService.getStudents().subscribe(students => {
      ...
    });
  }

  calculateAverage (arr) : number {
      var i, len=arr.length, average=0;

      for (i=0; i<len; i++) {
         average += arr[i];
      }

      return (average/arr.length);
    }
}

It is also advisable to remove the obj variable from the function as it is not used, and adjust the return type of your function to be number.

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

The memory usage steadily increases when you refresh data using the anychart gantt chart

I have a basic anychart code to update a gantt chart every second: function initializeSchedule(){ anychart.onDocumentReady(function () { anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) { documen ...

Navigating JSON within HTML forms

I'm reaching out because I have been using a workaround that seems to be effective, but I am concerned about potential issues down the line. To create an HTML form in PHP, I am using SimpleXML and DOM to manage the source code (an HTML file containin ...

Adding a specified number to a value in React: x + y

I am facing an issue with adjusting the value of deliveryFee based on the changing value of a variable weight. Initially, I have set specific values for deliveryFee based on different weight ranges: Up to 2 kg => $3.40 Up to 5 kg => $3.80 Up to 10 k ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...

Turn off the dynamically generated multiselect dropdown feature (using a plugin) in an angular application

I have included a multi-select dropdown in each row of a table, allowing the user to modify the selection and save it. The configuration for the multi-select dropdown is stored in a TypeScript file. Now, I am looking to disable the dropdown in certain ro ...

Bringing in Data with Angular

For my Angular projects, I attempted to utilize csv files in the following manner: import * as data1 from "./data.csv"; import * as data2 from "./data2.csv"; These files are situated in the same directory as the .ts file that I am trying to access them w ...

Steps for signing up for an event using addEventSource in fullCalendar

Whenever I click on the dayClick event, my goal is to add an event to the date that was clicked. This is the JavaScript code I currently have: $('#calendar').fullCalendar({ header: { center: "title", // The title appears in the center ...

How can I update an Angular Datatable to display new JSON data?

I have a Datatable controller set up as shown below: //Module / Módulo var angularDataTables = angular.module("angularDataTables", ['datatables', 'datatables.buttons' , 'datatables.bootstrap']); //Controller / Controlador ...

Need to Resend SMS Verification in Angular4 Firebase Phone Authentication? Here's How!

Currently, I am developing a project using angular 4 and ionic 3. One of the features in my project is implementing firebase phone authentication for the login page. While working on this, I encountered the need to add a functionality to resend OTP when ...

Discover every possible path combination

Looking to flatten an array of 1D arrays and simple elements, reporting all combinations until reaching a leaf "node." For example: // Given input array with single elements or 1D arrays: let input = [1, 2, [3, 4], [5, 6]]; The unfolding process splits pa ...

Angular 2: Implementing a Universal CSS Style Sheet

Is there a way to include a universal CSS file in Angular 2 applications? Currently, I have multiple components that share the same button styling, but each component has its own CSS file containing the styles. This setup makes it difficult to make changes ...

Determine the time left and check the speed of file uploads using ajax with jquery or javascript

Here is a snippet of code using jQuery.ajax to handle file uploads with progress tracking functionality. The function updates the DOM elements with information about bytes uploaded, total bytes, and percentage completed. However, I am looking for addition ...

The Angular Material Table experienced a collapse when trying to render over 20 columns simultaneously

Currently, I am experiencing an issue in Angular Version 5 where the Angular Material Table collapses when rendering more than 20 columns. Here is a snapshot of what my table looks like: https://i.stack.imgur.com/MXfvQ.png https://i.stack.imgur.com/XHWgq ...

Error: The validation of a JSON request failed as schema.validate is not a recognized function

As a beginner, I am currently immersed in a node.js API authentication tutorial. Everything was going smoothly until I had to refactor my code into separate files. Now, every time I send a JSON request via Postman, I keep encountering the error message "Ty ...

Avoid unintended double-tapping on mobile devices

On my main page, I have a button that triggers an overlay with item details, including buttons like one that reveals a phone number. An issue arises when a user accidentally double-clicks the main page button. The first click is processed on the main page ...

Explore the category options in the reference document using Node.js

Category Schema const CategorySchema = mongoose.Schema( { catName: { type: String, required: true } }, { timestamps: true } ); Product Schema const ProductSchema = new mongoose.Schema( { brand: { type: String, required: true }, title: ...

Using the as operator in TypeScript for type casting a string

function doSomething(a : any) { let b = (a as Array<any>) alert(typeof b) // displays "string" } doSomething("Hello") The alert is showing "string" instead of what I anticipated, which was something along the lines of a null value. The docu ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...

Loading a local CSS file upon opening a tab with a specific URL

When opening a tab to load a local HTML file from an addon (using addon-sdk), the following code is used: tabs.open({ url: self.data.url('index.html'), onReady: myScript }); However, there seems to be no straightforward way to include a CSS ...

Troubleshooting: React is not defined in Rollup + React 17 with updated JSX Transform

I'm currently working on prototyping a microfrontend architecture using Rollup and multiple create-react-app applications. However, when I try to locally yarn link my external app with the container app, I am encountering the following error: The err ...