ERROR TypeError: Cannot set property 'author' of undefined
Clash Royale CLAN TAG#URR8PPP
ERROR TypeError: Cannot set property 'author' of undefined
I get this error when i want to save changes to sever " add a comment" by clicking Submit button thanks for helping
onSubmit()
this.comment.author = this.author;
this.comment.rating = this.rating;
this.comment.comment = this.comment1;
this.comment.date = new Date().toISOString();
console.log(this.comment);
this.dishcopy.comments.push(this.comment);
this.dishcopy.save()
.subscribe(dish => this.dish = dish; console.log(this.dish); );
template code:
<div class="example-container">
<mat-form-field>
<input matInput placeholder="author" [(ngModel)]="author">
</mat-form-field>
<mat-form-field>
<mat-select placeholder="rating" [(ngModel)]='rating'>
<mat-option value="1">1</mat-option>
<mat-option value="2">2</mat-option>
<mat-option value="3">3</mat-option>
<mat-option value="4">4</mat-option>
<mat-option value="5">5</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<textarea matInput placeholder="comment" [(ngModel)]="comment1"></textarea>
</mat-form-field>
<button (click)="onSubmit()">Submit</button>
</div>
More deteils:
this is Comment.ts code:
export class Comment
rating: number;
comment: string;
author: string;
date: string;
and I instantiate it by:
import Comment from '../shared/comment';
...
comment:Comment;
1 Answer
1
It seems that you have never instantiated this.comment
, so when you try to access its author
property you find it undefined.
this.comment
author
add this code to the beginning of onSubmit()
onSubmit()
this.comment = new Comment();
Keep in mind that if you don't need some checks or logic operations into onSubmit()
you could bind directly this.comment
's properties to template variables
onSubmit()
this.comment
EDIT
This code comment:Comment;
is not an instantiation, is
a declaration. You need this:
comment:Comment;
comment: Comment = new Comment();
or this by letting TypeScript infer the type:
comment = new Comment();
Thanks for helping, it's worked.
– A.Rekik
Aug 6 at 10:18
so please accept my answer :)
– firegloves
Aug 6 at 10:19
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
so post the entire code please
– firegloves
Aug 6 at 10:03