Home > front end >  How declare a object in angular component
How declare a object in angular component

Time:07-07

I am newbie using Angular and I have an issue with object declaration in angular component

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
        }

}

when I try to compile this code I get 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 seems that danger propoerty in the class doesnt exist but it is there so give that error

Any help ?

CodePudding user response:

Typescript has more than sufficient information to figure out the object type by itself, so you can just do:

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 explicitly type it as Object, and evaluate this template line:

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

The Angular/TypeScript compiler will expect a value of type Object, which indeed has no danger property.

CodePudding user response:

I think you just need to add the type of variable propiedades to become like this.

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() {}
}
  • Related