[英]Cannot bind [(ngModel)] into angular html
我正在嘗試使用 angular 來實現編輯表單,但與 [(ngModel)] 綁定值時出現錯誤
錯誤類型錯誤:無法讀取未定義的屬性“名稱”
這是我的 typescript 代碼:
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);
});
}
}
這是我的 HTML 代碼:
<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>
我能做些什么來解決這個錯誤?
演示創建您的作者 model 而不是使用任何
export class Author{
public name:string="";
constructor(){}
}
然后在組件中
author: Author;
在 ngOnInit 或構造函數中初始化它
this.author=new Author();
您有此錯誤,因為author
未定義。 您可以向作者添加一個值,拋出一個構造函數,或者簡單地在聲明author: any = {};
或者,您可以僅顯示定義作者的form
:
<form class="border" *ngIf="!!author">
<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>
您必須初始化 object 作者。 因為起初 author.name 不存在。 解決方案:
// declare author such as
author = {};// not null
您看到的答案是作者未定義,並且whenever an instance is undefined but you try to access it's properties
也會出現此問題:例如:
[(ngModel)]="author.name" // But author is undefined, it'll tell you that the 'name' is undefined,
// instead of 'author' remember this.
But if [(ngModel)]="author" // This will never cause an error
還有一件事, author = {};
不會解決您的問題,您應該定義一個 class (推薦),如author = new author('Fes', 'Nguyen');
因為如果您不為其初始化或設置值,{} 就沒有屬性 pro!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.