Tips for utilizing the angular 6 class decorator within a component

I've recently developed an Angular 6 component that showcases the implementation of decorators. One of the decorators I've created is called @Course, with the value 'Angular 6' assigned to it. Now, I'm trying to figure out how to retrieve this value in the constructor of my component.

My goal is to log the value 'Angular 6' in the constructor. Is there a way to achieve this?

Although my code seems to be working fine and I am able to retrieve the value, I encountered an error in the command line:

ERROR in src/app/components/decorators/decorators.component.ts(19,22): error TS2339: Property
'course' does not exist on type 'DecoratorsComponent'.

import { Component, OnInit } from '@angular/core';

function Course(target) {
  Object.defineProperty(target.prototype, 'course', {
    value: () => "Angular 6"
  })
}

@Course
@Component({
  selector: 'app-decorators',
  templateUrl: './decorators.component.html',
  styleUrls: ['./decorators.component.scss']
})
export class DecoratorsComponent implements OnInit {

  constructor() {
    console.log(this.course());
  }

  ngOnInit() {
  }
}

Answer №1

destination.prototype.subject = () => 'React Native';

Answer №2

If you want to inform the TypeScript compiler about a dynamically added property, you can do so easily. One simple way is to add a decorator as shown in this example:

@Course
// ...
export class DecoratorsComponent implements OnInit {
    // ... 
    [key: string]: any;
}

Another approach is to access the dynamic property as you would an item in an array:

constructor() {

    const courseProp = this['course'];

    if (courseProp) {
        console.log(courseProp());
    }
}

Just remember to check for the existence of the property, as decorators can be removed at any time.

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

Accessing component instances of all components declared in HTML in Angular 7

In the works is a page that acts as a form creator. Users will be able to click and insert various components onto the page, resulting in entries being added to the "component" variable like this: Take Component1 for example: const childComponent = this. ...

What causes error TS2345 to appear when defining directives?

Attempting to transition an existing angular application to typescript (version 1.5.3): Shown below is the code snippet: 'use strict'; angular.module('x') .directive('tabsPane', TabsPane) function TabsPane(ite ...

Having difficulty loading Angular2/ Tomcat resources, specifically the JS files

I am currently in the process of deploying my Angular2 web application on a Tomcat server. After running the ng build command, I have been generating a dist folder and uploading it to my Tomcat server. However, whenever I try to run my web app, I encounte ...

In ReactJS with TypeScript, declaring a constant response after calling the login function using the await keyword

Currently tackling a task in React and Typescript where I am logging in as a user. Encountering an issue when trying to access the response variable, which leads to the following error: Object is of type 'unknown'.ts(2571) const response: unknow ...

Displaying the ngFor data in the HTML section

Struggling with passing an array from poll-vote.component.ts to poll-vote.component.html. The data involves radio buttons and I'm using ngFor loop with index, but it's not working as expected: Here is my poll-vote.component.ts code: import { Com ...

Is there an improved method for designing a schema?

Having 4 schemas in this example, namely Picture, Video, and Game, where each can have multiple Download instances. While this setup works well when searching downloads from the invoker side (Picture, Video, and Game), it becomes messy with multiple tables ...

Jasmine has detected an undefined dependency

Testing out the following code: constructor(drawingService: DrawingService) { super(drawingService); //... } private writeOnCanvas(): void { this.drawingService.clearCanvas(this.drawingService.previewCtx); this.drawing ...

Triggering createEffect in SolidJS with an external dependency: A guide

Is there a way to use an external dependency to trigger the createEffect function in Solid, similar to React's useEffect dependency array? I am trying to execute setShowMenu when there is a change in location.pathname. const location = useLocation() ...

Gatsby no longer hosts the website locally during certain tasks

My React and Gatsby project runs smoothly when I use Yarn start, it builds everything and serves the project on http://localhost:8000. However, whenever I perform specific operations like going to a 404 page or opening Chrome Dev tools, it suddenly stops s ...

Retrieving information selectively using useSWRImmutable

Having issues fetching data using useSWRImmutable. The problem arises when attempting to display the fetched data inside the UserRow component. Even though I can successfully print the data outside of the UserRow component, any console.log() statements wi ...

The parameter 'prev: todoType[] => todoType[]' cannot be assigned to the type 'todoType[]'.ts(2345)

An issue has arisen with this.props.update as mentioned in the title import { useState } from "react"; import axios from "axios"; import { todoType } from "../../types/todo"; type sendResponse = { task: string; }; type getRe ...

Files for the Express API and Sequelize are nowhere to be found

After collaborating with a Freelance developer for more than 10 months on a project, the developer suddenly disappeared without warning. Although he sent me a file containing the work he had completed, I realized that the backend API was missing. Project ...

UI not reflecting updated form validation after changes made

Currently, I have a situation where I am passing a form from the Parent component to the Child component. All the validations are being handled in the Parent component and the Child component is simply rendering it. However, there is a specific field calle ...

"Although the Set-cookie is present in the response header, it is not being properly

I developed a GraphQL server using apollo-server-express, and it is currently running on localhost:4000. Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header However, when checking the storage &g ...

Translate Firestore value updates into a TypeScript object

Here are the interfaces I'm working with: interface Item { data: string } interface Test { item: Item url: string } In Firestore, my data is stored in the following format: Collection Tests id: { item: { data: " ...

Updating a child component within a Modal: A step-by-step guide

I am using a global Modal component: export const ModalProvider = ({ children }: { children: React.ReactNode }) => { const [isModalOpen, setIsModalOpen] = React.useState(false); const [config, setConfig] = React.useState<ModalConfig | nu ...

Can a number value in a JSON object be converted to a string?

In my application, I have defined an interface: export interface Channel { canal: string; name: number; status: string; temperature: number; setpoint: number; permission: boolean; percentOut: number; } [UPDATE] in the HTML file: <input ...

Mastering the Art of Injecting Objects from the Server

Utilizing Angular Universal, I am serving my Angular application through an Express server. The objective is to embed an environment object (from the server) into my application. To achieve this, I have created an InjectionToken export const ENVIRONMENT ...

Showing Arrays in Angular on HTML Page

I have created an array that stores multiple arrays with 3 indexes each. An example of the structure looks like this: (3) [Array(3), Array(3), Array(3)] 0: (3) [199.4, 10.5, 19] 1: (3) [47.2, 2.1, 23] 2: (3) [133.6, 5.3, 25] In my HTML, I want to display ...

The error message "Identifier 'title' is not defined. '{}' does not contain such a member angular 8" indicates that the title variable is not recognized or defined in the

Here is the code snippet of my component: import { Router, ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { CategoriesService } from 'src/app/categories.service'; import { P ...