Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below:


@Component({
  selector: 'app-product-alerts',
  templateUrl: './product-alerts.component.html',
  styleUrls: ['./product-alerts.component.css']
})
export class ProductAlertsComponent {

//code ...

//code (imagine multiple methods) that can be isolated from the rest

 calculatesAge(){
  this.age ...
 }

 checkIdPermission() {
  this.permission ...
 }

//

}

You want to extract these methods into a separate class. However, the new class needs to inherit properties from ProductAlertsComponent. To achieve this, you create a separate file and implement the logic as follows:

//Separate file:
import {ProductAlertsComponent} from ".product-alerts.component.ts"

export class UserOperations extends ProductAlertsComponent {

 calculatesAge(){
  this.age ...
 }

 checkIdPermission() {
  this.permission ...
 }
}

The issue is that the template angular file (product-alerts.component.html) does not recognize calculatesAge() and checkIdPermission(). How can this problem be solved? Having a single class with numerous methods in ProductAlertsComponent is not sustainable in the long run. Is there a way to connect the extended class with the angular template file?

Answer №1

Take note that the template is specified within the @Component decorator, rather than directly in the class itself. This makes it easy to reuse the template as shown below:

@Component({
  selector: 'app-product-alerts',
  templateUrl: './product-alerts.component.html',
  styleUrls: ['./product-alerts.component.css']
})
export class ProductAlertsComponent {
// definition here
@Component({
  selector: 'app-user-operations',
  templateUrl: '../product-alerts/product-alerts.component.html',
  styleUrls: ['./product-alerts/product-alerts.component.css']
})
export class UserOperations extends ProductAlertsComponent {
    thatOneMethodThatIsOverwritten(): void {
    }
}

Answer №2

To utilize the functions from the TypeScript file, follow these steps:

Firstly, import your TypeScript file.

@ViewChild('mytypescript') public mytypescript: ProductAlertsComponent;

Then, you can proceed to use the methods as shown below:

this.mytypescript.calculatesAge();

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

Toggle the visibility of HTML elements by utilizing a JavaScript checkbox event

I have put together these JavaScript functions to hide the delivery address fields on my shopping cart address form if the goods are being sent to the billing address. The functions control the visibility of the HTML wrapped by... function getItem(id) { ...

What is the best way to implement two events in onPress using React Native?

I'm trying to implement the UploadB function and toggle the modal visibility using setModalVisible(!modalVisible)... However, my attempts so far have not been successful. const UploadB = useCallback(() => { dispatch({ type: ADD_P ...

Handling exceptions in Node.js is an essential part of writing reliable

Just a quick question: I seem to be dealing with an incorrect endpoint, and every time I run the code below, it results in an exception being thrown client.post("http://WrongEndPoint", [], function (data, response) { console.log("data:", data, "respo ...

transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated. var array = []; var maxLength = 3; var delay = 250; //Shortened the delay var ticker = {}; ...

Tips on cycling through hovered elements in a specific class periodically

I'm looking to add a hover animation to certain elements after a specific time, but I haven't been able to make it work correctly. Here's my attempted solution: CODE $(document).ready(function(){ function setHover() { $(' ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Recently added classes are not exhibiting the same behavior as the ones loaded during DOM ready

I have implemented a jQuery plugin called timeago.js to display the time a particular article was posted, for example, showing 2 minutes ago. HTML: <p> Articles <span class='post-time' title='2014-12-03 13:42'></span> ...

Is it necessary to encode special characters in a JSON object?

I am currently working on a code where I am taking a class and converting it to JSON format. Throughout my testing, all the content is surrounded by double quotes, for example: { "a" : "hello world ! '' this is john's desk" } I am wonderi ...

Utilize a web service within a service file and leverage it across multiple locations

I am seeking help with reusing a service function in different parts of my app, specifically to display a certain parameter ('title') in the HTML template. Firstly, I created a service: import { Injectable } from '@angular/core'; impo ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

Transferring information from a form without using specific authorization

Objective: The objective is to display data from a form where users input their name and favorite band. Upon submission, they will be redirected to a new page which will show: Name: John Doe Favorite Band: The Who Challenge: I am unable to utilize the ...

Submitting data with ajax in MVC when an option is chosen in a dropdown menu

Within my form, I have multiple dropdown lists. Whenever a user selects an option from one of these dropdowns, I want that value to be saved in the backend database. To avoid reloading the page, I believe using Ajax is the best approach, but I need assista ...

active option in Opencart 2.1 is set to "selected"

I've implemented the AJAX module d_quickcheckout to speed up the checkout process on opencart 2.1 (not the default one). However, I'm encountering an issue with a field in the payment address section that is always pre-selected with the region/st ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

How to address additional attributes received from the server in Next.JS

Encountering an error while trying to render a canvas with specified height and width within a child component in a NextJs app. The issue arises when attempting to integrate this mouse effect into my NextJS application. Everything functions correctly until ...

What is the reasoning behind the preference in Angular 2+ for storing shared variables in services instead of directly importing them from a constant object?

As I delve into creating a Single Page Application with Angular 7, I find myself questioning the prevalent recommendation of storing data in services as opposed to a file with constants that can be directly imported. The simplicity of directly importing a ...

Experimenting with the testing of two distinct functions

Hello, I am new to the world of testing and I would appreciate some guidance. I have two functions that I need help with. The first function is a bits-per-second converter that converts data into a more readable format. const convertBitrate = bitrate =&g ...

Why does the error message "$(…).functionName() is not a function" occur and what steps can be taken to prevent it from

I have encountered a console error message: $(...).functionName() is not a function Here is my function call: $("button").functionName(); This is the actual function: $.fn.functionName = function() { //Do Something }(jQuery); What ca ...

Leveraging the power of Angular.js to generate random user profiles

I am attempting to utilize the RUG (Random User Generator) API for a project, but I am struggling to make it function correctly. I have been trying to initiate an HTTP request after a click event, but unfortunately, it does not seem to be working as expect ...

Accessing a JSON file from a nearby location using JavaScript

I am currently working on an artistic project based on weather data, which will be hosted locally with the JSON file updating via FTP synchronization. This means that the JSON file will be sourced from the same computer where it is stored. The code snippet ...