Exploring the world of Angular 2 with prototyping and TypeScript

I am trying to implement a button that calls a function from a different component to open a modal form, passing the customer's name and an icon as parameters.

When I call the function like this:

@Component({
    selector: 'app-customer',
    templateUrl: './customer.component.html',
    providers: [Items]
})

export class Customers {
    @Input() customerName

    constructor() {}

    openDocs() {
         Items.prototype.openDocs(this.customerName, "fa-book")`;
    }
}

Everything works fine. But if I have it in the constructor and call it like:

constructor(private items: Items) {}

openDocs() {
    this.items.openDocs(this.customerName, "fa-book")`;
}

The parameters are not binding correctly.

Any explanation or suggestions would be greatly appreciated!

Update.. items.component.ts

import { Component } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { MainService } from '../services/main.service'

var JQuery = require('jquery');


@Component({
    selector: 'app-items',
    templateUrl: './items.component.html'

})


export class Items {
    public Title: string;
    public faIcon: string;    

    typeList = [

        {
            idType: "",
            dsType: ""
        }
    ]

    constructor(private http: Http, private mainService: MainService) {

    this.getItemsType();
    }

    getItemsType() {

        this.http.get('/Items/GetItemsType')
            .subscribe(data => {
                var objType = JSON.parse(data.json());                
                for (var i in objType) {
                    if (objType[i] != null) {
                        this.typeList.push(objType[i]);
                    }
                }              

            });

    }   

    openDocs(pTitle: string, pIcon: string) {

        this.Title = pTitle;
        this.faIcon = pIcon;
        JQuery('#docs').modal('show');

    }

    private closeDocs() {

            JQuery('#docs').css("display", "none");
            JQuery('#docs').modal('hide');

        }

    }

and the bind is two way

 <h4 ng-model="Title" ><i class="fa {{faIcon}}"></i> Add some list: {{Title}}</h4>

Answer №1

Parameters won't be bound correctly.

Try using an arrow function instead.

openDocs() {
    this.items.OpenDocs(this.customerNmane, "fa-book");
}

Change it to:

openDocs = () => {
    this.items.OpenDocs(this.customerNmane, "fa-book");
}

Reasoning Behind the Change

The use of arrow functions ensures that the correct context for this is maintained.

For More Information

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 function cannot be invoked. The 'Boolean' type does not have any call signatures. An error has occurred in the computed property of Vue3

Currently, I am working on creating a computed property that checks if an item is in the array. The function I have created returns a boolean value and takes one parameter, which is the item to be checked. isSelected: function (item: MediaGalleryItemTypes) ...

Obtain references to templates in component classes

<div> <input #ipt type="text"/> </div> Can the template access variable be retrieved from the component class? For example, is it possible to retrieve it as shown below: class XComponent{ somefunction(){ //Is it possible t ...

ng2-select2 prevent selection of initial value

My Angular project has the following setup: Hello.component.html <select2 ngDefaultControl [data]="list" [options]="{ placeholder: placeholder }" > </select2> Hello.component.ts list = [ { id: 1, text: 'Item 1 one' }, { i ...

Ways to resolve a library's reliance on node-exclusive modules

This is regarding the https://github.com/ecadlabs/taquito/ library, which is designed for use in both node applications and browser applications. However, it is assumed that the majority of users will utilize it in a browser environment. After integrating ...

Is there a way to include lazy loaded components in the production dist folder using angular-cli bundling?

For my development using angular-cli, I have executed the following commands and codes to construct my project. npm install angular-cli (angular-cli: 1.0.0-beta.10) ng new my-app ng g component lazy-me Then, I included a file named app.router.ts with t ...

What is the best way to execute a sequence of http requests only after the previous one has been completed successfully, while also addressing any

Working with Angular/rxjs 6 has brought me to a challenge. I'm struggling to get an observable sequence to run smoothly as intended. Here's the concept of what I'm trying to achieve: Request received to change systems: Check permissions Fe ...

Calculating the minimum value of a number in Angular 8

I attempted to convert a decimal number to a whole number and encountered an issue. When using the angular pipe method {{myNumber | number: '1.0-0.'}}, it provides a rounded off value instead of the floor value. For example, with number = 3.8, ...

Can you explain the purpose of typescript's tsserver?

Can you explain the role of tsserver? I understand that it assists IDEs in providing features such as error checking and auto-completion. However, I have been unable to locate any API documentation for it. ...

What is causing this TypeScript error to be raised by this statement?

Can you explain why the following statement is throwing a type error? const x: Chat = { ...doc.data(), id: doc.id } The error message states: Type '{ id: string; }' is missing the following properties from type 'Chat': message, name, ...

Ways to repair the mat-tab header

Within my application, I have five mat-tabs each containing a large amount of data which requires scrolling. Is there a way to fix the header of the tab while allowing the content to scroll? I attempted adding position:fixed; and position:sticky within: ...

Understanding how to deduce parameter types in TypeScript

How can I infer the parameter type? I am working on creating a state management library that is similar to Redux, but I am having trouble defining types for it. Here is the prototype: interface IModel<S, A> { state: S action: IActions<S, A&g ...

Jest came across a token from nestjs that it did not expect

I've hit a roadblock with running my end-to-end tests in Nest.js using Jest. Every time I attempt to execute my e2e test, an error keeps popping up Jest encountered an unexpected token Even though all other test suites ran smoothly, this particular ...

Angular ngFor directive allows for the creation of custom index increments when

Is there a way to implement custom index increment or decrement in ngFor? I'm looking for something along these lines: `<div *ngFor="let item of items; let i = index"> <span> {{items[i].name}} </span> <span&g ...

Having difficulty retrieving JSON data from a NodeJS server built with Typescript

My project involves using NodeJS + Express on the back end to send JSON data as a POST response to the front end through JQuery. I'm facing an issue where the message is not reaching the front end, which utilizes a JQuery AJAX call. It's puzzling ...

What is the process for displaying a custom component within a parent view component?

I am seeking to incorporate a custom component within mat-option. Below is the code snippet from my parent component: <mat-option *ngFor="let option of options" [value]="option.value"> HERE I WOULD LIKE TO INJECT SOME COMPONE ...

Using TypeScript to implement a nested static class with enforced generic type constraints

As an illustration, let's consider a basic linked list class in TypeScript version 3.7.5. A LinkedList<T> is composed of a series of ListNode<T>, where the type variable T remains consistent between them. In this scenario, a private static ...

Error in MEAN Stack: Unable to access the property 'companyTitle' because it is undefined

I have established a MongoDB collection named joblist in my database. Additionally, I have developed a DB schema known as jobList.js. var mongoose = require('mongoose'); const joblistSchema = mongoose.Schema({ companyTitle: String, jobT ...

Guide to Injecting a Service into a Custom Decorator in NestJS

Currently, I am working on developing a Custom Decorator to be applied in specific routes of my service. This decorator is responsible for validating a one-time password parameter. However, the challenge I am facing is that the validation method is located ...

Prevent ASP.NET Core routing from intercepting Angular 5 routing calls during deep linking operations

I am currently utilizing ASP.NET Core MVC for managing API calls, with routing set to api/*. Additionally, Angular 5.x is being used alongside its own routing system. Everything functions smoothly when running locally (Core on port 5000 and Angular on 420 ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...