1

I am new to angular.

On the project I created a component named as button and on the button.components.ts file I added the code of Input on import { Component, OnInit, **Input** } from '@angular/core'; and then afterwards I added the following code just above the button.component.ts constructor

@Input() text:string;

But it is throwing me an error on the word text, the error says,

Property 'text' has no initializer and is not definitely assigned in the constructor

The full code of the button.component.ts is as follows,

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

   @Component({
   selector: 'app-button',
   templateUrl: './button.component.html',
   styleUrls: ['./button.component.css']
   })
   export class ButtonComponent implements OnInit {
  
   @Input() text:string;

   constructor() { }

   ngOnInit(): void {
   }

   }

Referring to the link shared by @Rohith V when I initialize the text value inside the constructor it throws me an error on another component where I have called this button component.

Throws me an error on a component named as header.component.html

<header>
<h1>{{title}}</h1>
<app-button color="green" **text**="Add"></app-button>
</header>

The error says

Type 'string' is not assignable to type 'any[]'

The updated button.component.ts is as follows,

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

   @Component({
   selector: 'app-button',
   templateUrl: './button.component.html',
   styleUrls: ['./button.component.css']
   })
   export class ButtonComponent implements OnInit {
  
   @Input() text:any[];

   constructor() {
   this.text = [];
   }

   ngOnInit(): void {
   }

   }
  • https://stackoverflow.com/questions/49699067/property-has-no-initializer-and-is-not-definitely-assigned-in-the-construc Have a look on this post and it is already answered here – Rohith V Jun 20 '21 at 18:55
  • @RohithV Question updated – Aasif Nawasdeen Jun 20 '21 at 19:12
  • Check https://stackblitz.com/edit/angular-ivy-mkbtfk url you will get your answer – Suraj Tripathi Jun 21 '21 at 04:55
  • @SurajTripathi That was still causing the error but when I initialized the Input var into the `constructor` like `this.text = '';` it removed the error. Just added a empty string value to that. I am not sure if that's the correct workaround to this problem but anyway it solved it – Aasif Nawasdeen Jun 21 '21 at 13:07

0 Answers0