Create an instance of a TypeScript class within an Angular HTML template

Can TypeScript and Angular (6) be used in conjunction for this question?

Here is a model class example:

export class DropData {
   private readonly _originType: Component;
   private readonly _originRow: number;
   private readonly _originCol: number;
   private readonly _originComp: number;


   constructor(originType: Component, originRow: number, originCol: number, originComp: number) {
     this._originType = originType;
     this._originRow = originRow;
     this._originCol = originCol;
     this._originComp = originComp;
   }

export class Component {
  id: number;
  component: string;

  constructor(id: number, component: string) {
    this.id = id;
    this.component = component;
  }
 }

Is there a way to initialize this from an HTML template? The attempted method is shown below:

<div mwlDraggable
     [ghostElementTemplate]="dragging"
     [dropData]="new DropData(new PageComponent(component.id, componentManager.getComponentSimpleName(component.id)),rowIndex, colIndex, compIndex)"
     dragActiveClass="drag-active">
     <ng-template
        [appComp]="componentManager.getComponentSimpleName(component.id)"
        [id]="component.id">
     </ng-template>
</div>

(EDIT: The 'componentManager.getComponentSimpleName(component.id)' function, which returns a string, was accidentally omitted and should be included.)

EDIT2 The error encountered when accessing the page:

Uncaught Error: Template parse errors:
Parser Error: Unexpected token 'DropData' at column 5 in [new DropData(new 
PageComponent(component.id, componentManager.getComponentSimpleName(component.id)),rowIndex, colIndex, compIndex)] in ng:///AppModule/PageFoundationComponent.html@80:21 ("    <div mwlDraggable
                 [ghostElementTemplate]="dragging"
                 [ERROR ->][dropData]="new DropData(new 
PageComponent(component.id, componentManager.getComponentSimpleName(comp"): ng:///AppModule/PageFoundationComponent.html@80:21

Answer №1

Global variables are not directly accessible in templates.

In a template, you are limited to accessing only properties of the component. To access external data, such as the DropData object in this example, it must be defined as a property within the component:

public DropData: any = DropData;

This is similar to how you would reference an enum in a template. Trying to access other components like componentManager will also pose challenges. Such implementations highlight why embedding code in templates is not recommended. Templates should focus on displaying data while the component itself handles data management and retrieval tasks.

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

What is the best way to create an "equals" method for an interface in mongodb?

export interface IHealthPlanCard { _id: string, statusId: string; } const cards: IHealthPlanCard[] = await healthPlanCardsCollection.find(...) cards.filter(card => card.statusId.equals(cardStatusId)) I encountered an issue in this scenario: An ...

Incorporate TypeScript with Angular 2 to construct a dictionary with <key, value> pairs. Then, utilize a JSON file to populate the dictionary with data

I am in need of assistance with creating a dictionary or list with a specific structure. I have prepared a json file within my angular 2 project, and I would like to load this data into the dictionary that I am creating. Sample content from my Json file: ...

What is the procedure for inputting the settings for the export module in webpack?

I am currently working on setting up this webpack configuration file. However, I encountered an issue where the error message states that "any" is being used as a value instead of a type. How can I resolve this issue? module.exports:any = { ...

Simple method for adapting async/await function to function smoothly with observables

From my understanding, it's not recommended to use async/await methods in Angular. Therefore, I am exploring alternatives to achieve the desired functionality without using those methods. Currently, I am utilizing the canActivate function which call ...

Long loading times observed for larger datasets in Angular4 Datatable

I am currently experiencing slow loading times for my datatable when trying to display the data. The script is being called within the component like so: ngAfterViewInit() { $.getScript('./assets/js/datatables/datatable-basic.js'); } T ...

What prompts Angular to remove the contents of its output directory?

One thing I've noticed is that when building angular apps, it always creates a new output directory each time, deleting any previous existing folders. Why doesn't it just delete the directory content and reuse that folder instead? In my opinion ...

What are some ways I can incorporate fragments into my apollo-angular workflow?

Currently, I am using Angular 13 along with apollo-angular 3.0.0 and have implemented the GraphQL query codes as follows: const GET_TODOS = gql` query GetTodos() { todos() { id title brief body tags created_at ...

Why did the compilation of Next.js using TypeScript and ESLint succeed despite encountering errors?

I've been delving into Next.js and encountered unexpected results when integrating TypeScript and ESLint. ESLint seems to work well with TypeScript, but my project compilation is successful despite encountering errors. It's puzzling why the comp ...

Issue with NzPicker (nz-year-picker) due to absence of animation

Whenever I try to use the NzPicker, an error pops up on my screen. I'm encountering the same issue when adding the NzNoanimationModule. Is there a way to resolve this problem? <nz-year-picker (ngModelChange)="onChange($event)" nzPlaceHolder="sel ...

Combining and grouping objects by their IDs in a JavaScript array

Information: [ { "id": "ewq123", "name": "Joshua", "order": "Pizza" }, { "id": "ewq123", "name": "Joshua", "order": ...

How can I set up a KeyboardEvent listener in JavaScript?

My attempt to use @keydown resulted in an error: Type 'Event | KeyboardEvent' is not assignable to type 'KeyboardEvent'. Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, c ...

Utilizing Enum Lowercase as Index Key Type in TypeScript

Is there a way in TypeScript to use the lower case of an enum as an index key type? I have an enum defined as: export enum NameSet { Taxi = 'Taxi', Bus = 'Bus', Empty = '', } I want to define an object with keys based o ...

Adding a variable to this property in real-time

Is there a way to dynamically pass the item variable into this property? For example, if the item has a value of 35, is it possible for it to become this.BookingConfirmationFormsState35? onChange( event, item ){ console.log( this.BookingConfirmationF ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Challenges with Angular 4 service initialization

Having trouble with my authentication service. The constructor is being called 259 times when making an HTTP request, but only once when the call is removed. I am using a shared module to provide a unique instance of the service. Angular version: 4.4.4 C ...

Parent Class implementation for dynamic loading of components

I have been working on creating a new code for dynamic component loading using a parent-child relationship. The child component is set to override the parent and will be used for dynamically loading components. I found this useful link that guided me throu ...

What are the best methods for preserving programs in CentOS7?

Being new to Linux, I have been running programs on the server using the Windows Terminal. # gitbook build & # ng serve & However, every time I close the terminal window, it stops gitbook and angular. How can I keep them running continuously? I a ...

Executing a function when a user chooses to exit a webpage using the @HostListener('window:beforeunload') method

Utilizing @HostListener('window:beforeunload') allows me to detect when a user navigates away from the page, prompting a dialog window to open. I wish for an event to be triggered or a method to be executed if the user chooses to leave the page. ...

Unable to retrieve data from an API using a service in Angular2

[I am attempting to integrate this API file into Angular using a service. Previously, I had success with calling a local JSON file effortlessly, but I am encountering issues with this new one. The second image depicts the table layout I aim to create for t ...

Type ' ' cannot be assigned to type ''..ts(2322) ANOTHA ONE

Being a beginner in TypeScript and currently learning about enums, I encountered an error with the following example code that I cannot seem to understand. Here's the code snippet: enum Status { SUCCESS = 'success', FAILED = 'fa ...