The function _co.addCourse() is not recognized, despite being properly defined in the ts file

I am a beginner in Ionic-angular development and I am currently trying to create a function in my home.ts file and call it in my home.html file to perform a basic 'Create' operation on my FirebaseDB. Here is an excerpt from my home.html file:

home.html
    <ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
    <ion-buttons end>
        <button ion-button icon-only (click)="addCourse()">
          <ion-icon name="add"></ion-icon>
        </button>
      </ion-buttons>
  </ion-navbar>

</ion-header>

<ion-content padding>
</ion-content>

This section showcases my home.ts file:

home.ts
    import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from '../../../node_modules/rxjs';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  songsList: AngularFireList<any>;
  songs: Observable<any>;

  constructor(public navCtrl: NavController, public afDB: AngularFireDatabase, public alertCtrl: AlertController) {
    this.songsList = this.afDB.list('/songs');
    this.songs = this.songsList.valueChanges();

    function addCourse(){
      let prompt = this.alertCtrl.create({
        title: 'Course Name',
        message: "Enter the Course Code",
        inputs: [
          {
            name: 'title',
            placeholder: 'Title'
          },
        ],
        buttons: [
          {
            text: 'Cancel',
            handler: data => {
              console.log('Cancelled');
            }
          },
          {
            text: 'Save',
            handler: data => {
              const newSongRef = this.songs.push({});

              newSongRef.set({
                id: newSongRef.key,
                title: data.title
              });
            }
          }
        ]
      });
      prompt.present();
    }
  }

    }

Removing the declaration 'function' from function addCourse(){...} results in an error, but when viewing the website, I encounter the following message:

_co.addCourse() is not a function. (In '_co.addCourse()','_co.addCourse() is undefined)

Initially, I believed that moving the function outside of the constructor may resolve the issue. However, doing so raises questions about accessing the database or the Alert Controller.

Your assistance is greatly appreciated!

Answer №1

A recommended adjustment would be to remove the keyword "function" and place it outside of the constructor. Here's how you can modify it:

constructor(public navCtrl: NavController, public afDB: AngularFireDatabase, public alertCtrl: AlertController) {
}

addCourse(){
}

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

Using TypeScript to assign string array values to object properties

I am working with a string array: values: string['myName', 'myLastname', 'myAge'] and my goal is to assign each value to a property of an object like this: myModel={name:'', lastname:'', age:''} o ...

The type {properties .....} is incompatible with the type ActionReducer<AdminState, Action> in Angular 12 using NGRX

Implementing NGRX library for redux to organize the state of the application in a structured way: export interface ApplicationState { adminState: AdminState } export interface AdminState { adminProductCategory: ProductCategoryState; adminProdu ...

Creating a brand new Schema in Mongoose for a post sub-array utilizing ng-select technology

Here is the Schema I am working with: const userSchema = new Schema({ email: String, skills: { name: String, label: String } }) module.exports = mongoose.model('user', userSchema, &apos ...

The parameter of type 'Element' cannot be assigned a value of type 'string'

For my latest project, I needed a section that could be resized by dragging one of the element's corner bars. After some research on Youtube, I stumbled upon "THE ART OF CODING" who demonstrated this feature using JavaScript without importing any pack ...

Strategies for passing multiple props to a function in React using TypeScript, such as useState([]) and useState(boolean)

Dealing with API Structure { "default": [ { "id": 1, "name": "A" }, { "id": 2, "name": "B" }, { "id": 3, "name" ...

variable within the scope of a function

Currently, I am working on an app where I need to capture a few images using Ionic and Angular. There are 3 buttons, each responsible for capturing a picture. Here is the HTML code snippet: <img ng-src="{{srcImage1 || 'img/default_image.png' ...

Laravel 5.7 not receiving form data when submitted from Angular 7

I am currently working with Angular 7 and Laravel 5.7. My objective is to send data from Angular to Laravel. Below is the snippet of my Angular 7 code responsible for posting data to the Laravel API: const target = event.target; const name = targ ...

Using Node.js to efficiently post JSON data in bulk through an API

I am working on a project that involves using Angular2 for the frontend and Nodejs API with 'mssql' NPM package to interact with a Microsoft SQL Server. Everything is functioning as expected, but I'm stuck on one specific task. My challeng ...

TS2339 error caused by update to Typescript v2.2.2 union type

Within my Angular 2 project, I am utilizing ngrx for managing state with actions and reducers. An example of the actions setup is as follows: import { Action } from '@ngrx/store'; export const actionTypes = { ACTION_1: type('Actions 1&ap ...

Tips for modifying the data type of a property when it is retrieved from a function

Currently, I have a function called useGetAuthorizationWrapper() that returns data in the format of { data: unknown }. However, I actually need this data to be returned as an array. Due to the unknown type of the data, when I try to use data.length, I enc ...

What are the benefits of combining 'eslint' and 'typescript-eslint' for TypeScript linting as opposed to just using 'tsc'?

Objective: Developing a rigorous TypeScript linter script eslint scans for problematic JavaScript code patterns. The documentation recommends initiating eslint with npm init @eslint/config@latest This process also installs typescript-eslint But what is ...

Action buttons on material cards extend beyond the boundaries of the card content on both the left and right sides

Check out this Angular 10.2 Material sample where the action buttons on the right and left extend beyond the card-content: https://i.sstatic.net/Btxy1.png The "Create account" button's right edge should align with the right edge of the fields, and t ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

Create an interface property value that behaves like Array.join(), but only accepts values from the keyof keyword

I am currently working with two interfaces: interface A { foo: string; bar: string; baz: string; } and: interface B { field: keyof A; } With interface B, I can set the field as 'foo' like this: const b: B = { field: 'foo' } ...

Troubleshooting: Directives in Angular 4 not recognizing RegEx patterns

I have developed a directive that validates the input in a text field, allowing users to enter numbers, dots, and commas. However, the validator only seems to work for numbers and not for commas and dots. import { Directive, ElementRef, HostListener } fro ...

Angular 2 Endgame: HostBinding feature no longer functional

Here is how I used host-binding on a button attribute named "disabled" in the parent component of ng2-RC4: @Component({ selector: "nav-next", template: ` <div class="nav-next-directive" (click)="onClick($event)"> <button color ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

Angular: Error when TypeScript object returns an array object value

I have encountered a strange issue where the array value returned as [object Set] when I console log it. It's unclear whether this problem is occurring in the component or the service, but the object values are not being displayed. This issue arises ...

Obtain both the key and value from an Object using Angular 2 or later

I have a unique Object structure that looks like this: myCustomComponent.ts this.customDetails = this.newParameter.details; //the custom object details are: //{0: "uniqueInfo", // 5: "differentInfo"} The information stored in my ...

The Bootstrap modal backdrop is now displaying prominently in front of the modal following the latest Chrome update

Chrome version: Version 111.0.5563.64 (Official Build) (x86_64) Bootstrap: 4.3.1 Recently, there has been an issue with the modal backdrop appearing in front of the modal itself after a Chrome update. The problem does not seem to be related to z-index, an ...