'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 1:[1]
You have to declare the type of the property named after 'question'. You can try following,
question:any = {};
It's a typescript strict type checking issue of recent update version. If you are using Angular then you can easily turn off this strict type checking by this way, Turn off strict type checking in Angular
Solution 2:[2]
You should change the type of question object to any
question: any = {};
Or
Create an interface :
interface Question {
text?: string;
// other properties if you have ones
}
And then set the type of question to Question
question: Question = {}
here is a working example
Solution 3:[3]
It is because you do not have any keys name "text" in your object "question" You can either add one key named "text" in the object or you can provide type definition to you object "question" . something like below:
interface Iobject {
text: string;
}
question: Iobject;
By doing this your error will be gone.
Solution 4:[4]
This helps with any:
let a : any = {};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sourav Das |
| Solution 2 | Ismail Dinar |
| Solution 3 | Mr.UV |
| Solution 4 | Sachini Witharana |
