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

在我的数据库中,我有很多用户,他们有很多食谱。每个食谱都有一些属性和成分集合。

因此,当用户在页面上显示要编辑的配方时,应该会出现(表格)加载了当前数据的配方。这是一种工作,因为我可以看到数据,但我认为它做得不好。

我的表格在没有数组(成分)的情况下工作正常。你能告诉我应该如何将成分添加到我的编辑表单中吗?

如果您看到我的代码并给我反馈并提示我应该更改什么,我将不胜感激。

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);

    });

  }


}


慕码人8056858
浏览 118回答 1
1回答

叮当猫咪

问题是必须定义表单上的属性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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript