0

When I define inside my component in angular the instance variable like that: import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', //template: ``
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Welcome';
  nombre1 : number;
 
  
}

I have a red line below nombre1. The error is :

Property 'nombre1' has no initializer and is not definitely assigned in the constructor.ts(256

Can someone please tell me where is my error.

3
  • What's the error? Commented Aug 27, 2021 at 4:37
  • What's the TS compiler error message associated with the red line? The syntax is fine. Commented Aug 27, 2021 at 4:37
  • @seesharper check please the updated post Commented Aug 27, 2021 at 4:39

3 Answers 3

1

The error is caused by the fact that you have declared your field as not being able to accept undefined, but you have not supplied a non-undefined value to it.

Either make the field able to accept undefined...

nombre1: number | undefined;
// or: nombre1?: number;

...or supply the default value:

nombre1: number = 0;
// or: assign it in constructor
Sign up to request clarification or add additional context in comments.

Comments

1

I have encountered with this many times. And i believe if you are using Visual studio code you will get hints on what to do.

What i normally do is add some initializer or a exclamation just after the variable name. As in your code it would be as follows :

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', //template: ``
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title: string = 'Welcome';
  nombre1!: number;  
}

Note: You have to specify what datatype you are dealing with. Also if you dont want to give any value as initializer just use ! right after the variable name as shown.

Hope the issue is resolved.

Comments

-1

You have to use = instead :

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  title= 'Hola ';
  nombre= 'john';
}

app.component.html:

<hello title="{{ title }}" nombre="{{ nombre}}"></hello>

hello.component.ts:

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

    @Component({
      selector: 'hello',
      template: `<h1>{{title}} {{nombre}}! </h1>`,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class HelloComponent  {
      @Input() title: string;
      @Input() nombre: string;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.