What is the syntax for declaring an object within an Angular component?

Hello there, I'm fairly new to Angular and I've been encountering an issue with object declaration in one of my angular components.

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

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

})
export class ClasesComponent
{

  alerta:string="alert-danger";

  constructor() {  }

  propiedades:Object = {
    danger: false
  }

}

Whenever I try to compile this code, I encounter an error:

***Compiled with problems:

Error: src/app/components/clases/clases.component.html:9:76 - error TS2339: Property 'danger' does not exist on type 'Object'.

9 <h3 [ngClass]="{'text-danger':propiedades.danger,'text-info':!propiedades.danger}"><
                                                                             ~~~~~~

  src/app/components/clases/clases.component.ts:5:16
    5   templateUrl: './clases.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component ClasesComponent.

It appears that the 'danger' property in the class is not recognized causing this error to be thrown.

Any suggestions or help would be greatly appreciated!

Answer №1

To achieve the desired outcome, simply specify the type of variable propiedades as shown in the code snippet below.

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

@Component({
  selector: 'app-clases',
  templateUrl: './clases.component.html'
})
export class ClasesComponent {
  alerta = 'alert-danger';
 
  propiedades: {danger: boolean} = {
    danger: false
  };

  constructor() {}
}

Answer №2

With Typescript, you can rely on its ability to determine the object type automatically. This means you don't have to explicitly define it as shown below:

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

@Component({
  selector: 'app-clases',
  templateUrl: './clases.component.html'
})
export class ClasesComponent {
  alerta = 'alert-danger';
 
  propiedades = {
    danger: false
  };

  constructor() {}
}

If you were to specify the type as Object, and use this line in your template:

<h3 [ngClass]=" {'text-danger':propiedades.danger,'text-info':!propiedades.danger }">

The Angular/TypeScript compiler would expect the value to be an Object, which doesn't have a danger property.

Answer №3

In TypeScript, declaring Objects using interfaces can be done in 2 ways.


The first way is to use an interface when the exact keys are known:

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

interface Properties {
    danger: Boolean;    
}

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

})
export class ClassesComponent
{

  alert:string="alert-danger";

  constructor() {  }

  properties: Properties = {
    danger: false
  }

}

The second way is to use an interface when the exact keys are not known:

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

interface Properties {
    [key: string]: Boolean;    
}

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

})
export class ClassesComponent
{

  alert:string="alert-danger";

  constructor() {  }

  properties: Properties = {
    danger: false
  }

}

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

Why is my Angular proxy failing to rewrite the path when making an HTTP GET request?

I am facing an issue with my proxy configuration where it is not redirecting as expected based on the rewrite configuration. You can find my proxy.config.json below: { "/sap": { "target" : "http://server.domain.com:8002", "secure" : fa ...

Ways to apply CSS class styles when a button is clicked in Angular

How can I create a button that toggles between light and dark mode when clicked, changing the background color and font color accordingly? I need to add CSS classes .bgdark and .textlight to the 'mainbody' for dark mode. HTML <div cla ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

Using Angular components to manipulate the CSS in the DOM

Struggling with dom manipulation in an angular/node.js environment using typescript for my visualcomponent.html The second inline styling works fine, showing the h1 in blue color. However, I run into issues when trying to embed strings within the innerHTM ...

Error is being thrown due to defining a variable after it has already been declared and

Before I use a variable, I encountered the issue of using it before its definition, interface IProps extends WithStyles<typeof STYLES>; const STYLES = () => ({ }) Although it didn't cause any errors, a warning appeared: STYLES used befo ...

What is the best method to determine the cumulative time spent filling out a text box on a web page using Angular?

I am working on a web page that contains two text boxes. My goal is to track the total time spent inside each box when the user clicks the submit button at the end of the page. clickInside() { this.text = 'clicked inside'; this.wasIns ...

Exploring how to iterate through an object to locate a specific value with TypeScript and React

I am looking to hide a button if there is at least one order with status 'ACCEPTED' or 'DONE' in any area or subareas. How can I achieve hiding the "Hide me" menu item when there is at least one area with orders having status 'ACCE ...

Disabling ESLint errors is not possible within a React environment

I encountered an eslint error while attempting to commit the branch 147:14 error Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions I'm struggling to identify the issue in the code, even ...

Seeking guidance for the Angular Alert Service

I'm relatively new to using Angular and I'm struggling to determine the correct placement for my AlertService and module imports. Currently, I have it imported in my core module, which is then imported in my app module. The AlertService functions ...

AngularYelp: Node Integration for Enhanced Functionality

Embarking on a new learning journey here, so please bear with me... Discovered node-yelp while browsing Yelp's API docs. Check it out here. // Request API access: http://www.yelp.com/developers/getting_started/api_access var Yelp = require('yel ...

Managing two select fields in a dynamic Angular form - best practices

On my screen, I am dynamically creating elements using a reactive form. Specifically, I am creating cards with two selection fields each: https://i.sstatic.net/WUvQH.png Situation: When I add a card and choose a layout, the options for that specific layo ...

I need help with querying the date format in Mongoose and MongoDB. The specific date I am trying to query is stored in the field "ticketTimeStartDate" and is in the format: "Mon Oct 18 2021 12:28:59 GMT+0000 (

Can anyone provide guidance on querying this specific date format in moongose and MongoDB? The date field is as follows: "ticketTimeStartDate": "Mon Oct 18 2021 12:28:59 GMT+0000 (Coordinated Universal Time)", ...

Angular fails to combine values within routerLink

The issue is straightforward - I have a component that retrieves the last searched items saved in sessionStorage as an array of ListItem objects: export class SearchlistComponent { results = JSON.parse(<string>sessionStorage.getItem("lastSear ...

What is the reasoning behind TypeScript's decision to permit the omission of a function's return type?

After setting noImplicitAny to true in my tsconfig, I was surprised to find that I could still omit function return types. One instance is a getter function as shown below: get name() { return `${this.valueName} of ${this.suitName}`; } Inquiry 1: Can ...

Are there any specific events in PrimeNg's p-calendar that trigger when the time is changed?

In my project, I utilized PrimeNg v5.2.7 for the From Date and To Date fields. I implemented minDate validation on the To Date field. However, I encountered a scenario where if I select 30th Jan 2021 as the From Date and only adjust the time in the To Da ...

Unveiling the Client Machine's MAC Address in C# MVC

Trying to obtain the Mac Address of a local or client's machine, but encountering the issue of receiving the same Mac address on any device or computer. The code being used is as follows: string macAddresses = null; NetworkInterface[] nics = NetworkI ...

Keep an eye out for any instances of new files being created in nodemon js or npm

Is there a way to monitor only for new file creation events using nodemon js, npm, or any other packages? For instance, in a project, whenever a new file is created, a specific script needs to be executed to carry out additional tasks for a one-time setup. ...

The web control I'm trying to use isn't showing up on my webpage when it's located in a separate folder

I am facing an issue where my web control is not showing up on my web page when it is in a different folder. However, it works perfectly fine when placed in another web page in the same location. Here is a snippet of my source code : .. <%Register sr ...

Filter and transfer data from one Angular array to another

As a newcomer to Angular, I am working with an array of events containing multiple arguments. My goal is to filter these events and separate them into two new arrays: upcoming events and past events. Below is a snippet of the TypeScript code I am using: a ...

What is preventing me from setting the User object to null in my Angular application?

Currently, I am working on a project in Angular and encountering a specific issue. In my service class, the structure looks like this: export class AuthService { authchange: new Subject<boolean>(); private user: User; registerUser(authD ...