为了账号安全,请及时绑定邮箱和手机立即绑定

在 Angular 中制作 editForm 最简单的方法是什么?

在 Angular 中制作 editForm 最简单的方法是什么?

慕码人8056858 2023-06-09 17:52:00
在我的数据库中,我有很多用户,他们有很多食谱。每个食谱都有一些属性和成分集合。因此,当用户在页面上显示要编辑的配方时,应该会出现(表格)加载了当前数据的配方。这是一种工作,因为我可以看到数据,但我认为它做得不好。我的表格在没有数组(成分)的情况下工作正常。你能告诉我应该如何将成分添加到我的编辑表单中吗?如果您看到我的代码并给我反馈并提示我应该更改什么,我将不胜感激。export class RecipeEditComponent implements OnInit {  @ViewChild('editForm') editForm: NgForm;  recipe: IRecipe;  photos: IPhoto[] = [];  ingredients: IIngredient[] = [];  uploader: FileUploader;  hasBaseDropZoneOver = false;  baseUrl = environment.apiUrl;    currentMain: IPhoto;  constructor(private route: ActivatedRoute, private recipeService: RecipeService,    private toastr: ToastrService) { }  ngOnInit(): void {    this.loadRecipe();    }  loadRecipe() {    this.recipeService.getRecipe(this.route.snapshot.params.id).subscribe(recipe => {      this.recipe = recipe;      this.initializeUploader();    })  }  updateRecipe(id: number) {    this.recipeService.editRecipe(id, this.recipe).subscribe(next => {      this.toastr.success('Recipe updated successfully');      this.editForm.reset(this.recipe);    }, error => {      this.toastr.error(error);    });  }}
查看完整描述

1 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

问题是必须定义表单上的属性name,以便 Angular 知道要更新哪个输入。您将 name 绑定到可编辑模型设置的同一属性,这意味着用户可以编辑它,实际上可以删除它,这不好。


解决方案是将其更改为不会更改的唯一值。这应该有效:


<div *ngFor="let ingredient of recipe.ingredients; let i = index">

    <input class="form-control" type="text" name="name{{ingredient.id}}" [(ngModel)]="ingredient.name">

    <input class="form-control" type="text" name="amount{{ingredient.id}}" [(ngModel)]="ingredient.amount">

  </div>

</div>

查看完整回答
反对 回复 2023-06-09
  • 1 回答
  • 0 关注
  • 106 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信