Reputation: 1040
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.
Upvotes: 0
Views: 697
Reputation: 35
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.
Upvotes: 1
Reputation: 52107
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
Upvotes: 1
Reputation: 85
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;
}
Upvotes: -1