Angular - Property has no initializer and is not definitely assigned in the constructor.

By Hardik Savani October 20, 2023 Category : Angular

Hi,

In this tute, we will discuss angular property has no initializer and is not definitely assigned in the constructor. This article will give you simple example of angular formgroup has no initializer and is not definitely assigned in the constructor. let’s discuss about viewchild property has no initializer and is not definitely assigned in the constructor solved.

Few days ago i was working on my angular 13 app and i was getting following error for define id:

"Property 'id' has no initializer and is not definitely assigned in the constructor."

because i was using my angular 12 code. I will show what was that code and what is solution. let's see both and also look solution:

Old Code:

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

@Component({

selector: 'app-view',

templateUrl: './view.component.html',

styleUrls: ['./view.component.css']

})

export class ViewComponent implements OnInit {

id: number;

}

Solution: you need to add "!" after variable

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

@Component({

selector: 'app-view',

templateUrl: './view.component.html',

styleUrls: ['./view.component.css']

})

export class ViewComponent implements OnInit {

id!: number;

}

If you are creating interface then you can solve by following ways.

Solution 1:

export interface Post {

id!: number;

title!: string;

}

Solution 1:

export interface Post {

id: number = '';

title: string = '';

}

I hope it can help you....

Tags :
Shares