I am trying to achieve edit form with angular and I am having an error from binding value with [(ngModel)]
ERROR TypeError: Cannot read property 'name' of undefined
Here is my typescript code:
import { Component, OnInit } from "@angular/core";
import { HttpService } from "./../http.service";
import { ActivatedRoute, Router } from "@angular/router";
@Component({
selector: "app-edit",
templateUrl: "./edit.component.html",
styleUrls: ["./edit.component.scss"],
})
export class EditComponent implements OnInit {
id: string;
private sub: any;
author: any;
error: any;
constructor(
private _httpService: HttpService,
private _route: ActivatedRoute,
private _router: Router
) {}
ngOnInit() {
this.sub = this._route.params.subscribe((params) => {
this.id = params["id"];
});
this.oneAuthorInfoRetrieve();
}
oneAuthorInfoRetrieve() {
let observable = this._httpService.getOneTask(this.id);
observable.subscribe((data) => {
console.log("Successfully got data from get one author", data);
this.author = data["data"];
});
}
onEdit() {
let observable = this._httpService.editTask(this.id, this.author);
observable.subscribe((data) => {
console.log("Successfully update", data);
});
}
}
And here is my HTML code:
<a [routerLink]="['/home']"> Home </a>
<b>
<p>Edit this Author:</p>
</b>
<form class="border">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" class="form-control" name="name" [(ngModel)]="author.name">
</div>
<div class="form-group">
<button class="btn btn-danger" id="cancel">Cancel</button>
<button class="btn btn-primary" id="submit" (click)="onEdit()">Submit</button>
</div>
</form>
What can I do to fix this error?