Angular onSubmit方法在Form Edit

时间:2019-08-03 07:51:44

标签: html angular forms split

在编辑中调用onSubmit方法时,Form给出“ get(...)。value.split不是函数”错误。

// Form的onSubmit()方法

onSubmitRecipe(f: FormGroup) {
    // Convert string of ingredients to string[] by ','
    console.log('ID in modal before submitting is: ' + this.id);
    console.log("Ingredients: " + f.get('ingredients').value);
    let data = {
      "id": this.id,
      "imageLink": f.get('imageLink').value,
      "name": f.get('recipeName').value,
      "description": f.get('description').value,
      "ingredients": f.get('ingredients').value.split(','), // TODO: Somehow errors out when no value is input by the user when submitting the form
      "timeNeeded": f.get('timeNeeded').value,
      "favourite": f.get('favourite').value,
    }
...

//表单HTML

<ion-item>
            <ion-label position="floating">Ingredients: <ion-text color="danger">*</ion-text>
            </ion-label>
            <ion-input required formControlName="ingredients" type="text" placeholder="Split ingredients with a comma ','"></ion-input>
</ion-item>

应该期望一个字符串[]。

如果我按一下输入/编辑成分,则可以很好地提交表格。仅当我在不触摸配料输入的情况下编辑表格时才会出错。

错误:

f.get(...).value.split is not a function
    at RecipeModalPage.onSubmitRecipe (recipe-modal.page.ts:91)
    at Object.eval [as handleEvent] (RecipeModalPage.html:65)
    at handleEvent (core.js:34789)
    at callWithDebugContext (core.js:36407)
    at Object.debugHandleEvent [as handleEvent] (core.js:36043)
    at dispatchEvent (core.js:22533)
    at core.js:33721
    at HTMLElement.<anonymous> (platform-browser.js:1789)
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:30885)

2 个答案:

答案 0 :(得分:0)

我不知道您的问题是要解决成分为空的问题,它应该具有字符串或解决拆分错误。

  

我将回答解决拆分错误

"ingredients": f.get('ingredients') ? f.get('ingredients').value.split(','): [],

将您的对象关键字组成行更改为上述代码。

答案 1 :(得分:0)

您的console.log(f.get('ingredients').value)返回(2) ["ingredient 1", " ingredient 2"]

这意味着初始值设置为array,在该值上您不能调用.split()方法。您只能在string上调用它。

因此,将值初始化为"ingredient 1, ingredient 2"。看看是否可行。

相关问题