Search code examples
angulartypescriptangular-materialangular11

TS2339: Property 'text' does not exist on type '{}'


I am actually facing this line problem :- <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">here .text extension make problem. Here I used Angular11. here is my code.

Question.component.html

<mat-card >

<mat-card-content>

<form>
   
    <mat-form-field>
      <mat-label>Question</mat-label>
      <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">
    </mat-form-field>
  
  </form>
</mat-card-content>


<mat-card-actions>
    <button (click)="post(question)" mat-button>POST</button>
</mat-card-actions>


</mat-card>

question.component.ts

import {Component} from '@angular/core'
import {ApiService} from './api.service'

@Component({

   selector:'question',
   templateUrl:'./question.component.html'

})

export class QuestionComponent{

    question = {}

    constructor(private api:ApiService){}

    post(question)
    {
        this.api.postQuestion(question);
    }
}

when i run my application.then i found these error:-

src/app/question.component.ts:7:16
    7    templateUrl:'./question.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component QuestionComponent.


Error: src/app/question.component.html:9:36 - error TS2339: Property 'text' does not exist on type '{}'.

9       <input [(ngModel)]="question.text" name="question" matInput placeholder="Question">
                                     ~~~~

  src/app/question.component.ts:7:16
    7    templateUrl:'./question.component.html'
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component QuestionComponent.

How I resolve this issue?


Solution

  • Problem

    when you create an object question = {} Typescript infers the type as {} an object without properties. If you try to access any property, it will throw an error

    Solution

    Set the type of the object

    question: { text?: string; } = {}
    

    Or even better declare an interface

    interface IQuestion {
      text?: string;
    }
    
    ...
    question: IQuestion = {}