英文:
Cannot assign value "undefined" to template variable "buttonName". Template variables are read-only. Angular/TypeScript
问题
所以我想说我是Angular的新手。
app.component.ts;
model = new Model();
addItem(value: string) {
if (value !== "") {
this.model.items.push(new TodoItems(value, false));
}
}
model.ts;
export class TodoItems {
description;
action;
constructor(description: string, action: boolean) {
this.description = description;
this.action = action;
}
}
app.component.html;
<input type="text" #buttonName class="form-control">
<div class="input-group-append">
<button class="btn btn-primary" (click)="addItem(buttonName.value); buttonName=''">Add</button>
</div>
我如何解决这个错误?
英文:
So I want to say Im new for Angular.
app.component.ts;
model = new Model();
addItem(value:string){
if(value!="")
{this.model.items.push(new TodoItems(value,false));}
model.ts;
export class TodoItems{
description;
action;
constructor(description: string,action: boolean){
this.description= description;
this.action = action;
}
}
app.component.html;
<input type="text" #buttonName class="form-control">
<div class="input-group-append">
<button class="btn btn-primary" (click)="addItem(buttonName.value); buttonName='';">Add</button>
</div>
How I can solve this error?
答案1
得分: 1
你应该在组件中处理 todoText
状态的更改(尽管我看不到它的任何用途),而不是在模板中。所以我猜你想要清除内容,这样你可以在执行的函数中处理它。
我稍微重写了组件。
如果你继续收到错误,请分享 app.component
,因为它不太清楚是否定义正确。
app.component.ts
export class AppComponent {
todoText = '';
model = new Model();
public addItem(value: string) {
if (value != '') {
this.todoText = ''; // 在这里管理 todoText
this.model.items.push(new TodoItems(value, false));
}
}
}
app.component.html
<input type="text" #buttonName class="form-control" />
<div class="input-group-append">
<button
class="btn btn-primary"
(click)="addItem(buttonName.value);"
>
Add
</button>
</div>
英文:
You should handle the shange of status of todoText
in the component (Even though I don't see any use of it), not the template. So I'm guessing you want to clear the content, so you can handle it in the function you execute.
I rewrote the component a bit.
If you keep getting the error, please share app.component, since it isn't that clear if it is well defined.
app.component.ts
export class AppComponent {
todoText = '';
model = new Model();
public addItem(value: string) {
if (value != '') {
this.todoText = ''; //Manages the todoText here
this.model.items.push(new TodoItems(value,false));
}
}
}
app.component.html
<input type="text" #buttonName class="form-control" />
<div class="input-group-append">
<button
class="btn btn-primary"
(click)="addItem(buttonName.value);"
>
Add
</button>
</div>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论