Angular 2 - 由JQuery代码设置的Form元素值未与其他手动输入的表单数据一起提交

时间:2017-12-07 21:50:00

标签: angular angular2-forms

我设计了一个角度2应用程序,允许用户通过填写​​html表单来创建新配方。如果用户手动在表单中输入值,则单击提交按钮时,所有这些值都将传递给我的服务代码。问题是我有一个表单元素,在按下提交按钮之前由JQuery脚本更新,但是当单击提交按钮然后查看提交的表单数据的内容时,此表单元素没有任何价值。我真的不明白为什么,因为我可以在屏幕上看到表格中的值。如果我手动在此表单元素中输入值,则数据将在表单数据中正确提交。

下面是我的HTML(由JQuery设置其值的元素是元素id =“image_id”“): -

<div class="row">
  <div class="col-md-12">
    <form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">
      <table class="table table-hover table-responsive table-bordered">
        <tr>
          <td>
            Name
          </td>
          <td>
            <input name="name" formControlName="name" type="text" class="form-control" required />
            <div *ngIf="create_recipe_form.get('name').touched && create_recipe_form.get('name').hasError('required')"
              class="alert alert-danger">Name is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Image
          </td>
          <td>
            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input name="image_id" formControlName="image_id" type="text" class="form-control" id="image_id" />
          </td>
          <td>
        </tr>

        <tr>
          <td></td>
          <td>
            <button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
                <span class="glyphicon glyphicon-plus"></span> Create
            </button>
          </td>
        </tr>
      </table>
    </form>
  </div>
</div>

My Angular 2组件文件如下所示: -

import { Component, Input, Output, EventEmitter, OnInit, ElementRef } from 

'@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

import { CategoryService } from '../category.service';
import { RecipeService } from '../recipe.service';
import { DifficultyService } from '../difficulty.service';
import { IngredientService } from '../ingredient.service';
import { ImageService } from '../image.service';

import { Recipe } from '../recipe';
import { Category } from '../category';
import { Difficulty } from '../difficulty';
import { Ingredient } from '../ingredient';

import $ from "jquery";

@Component({
  selector: 'app-create-recipe',
  templateUrl: './create-recipe.component.html',
  styleUrls: ['./create-recipe.component.css'],
  providers: [RecipeService, ImageService]
})

export class CreateRecipeComponent implements OnInit {

  create_recipe_form: FormGroup;

  @Output() show_read_recipes_event = new EventEmitter();

  imageId: number;

  constructor(
    private _recipeService: RecipeService,
    private _imageService: ImageService,
    formBuilder: FormBuilder,
    private elem: ElementRef
  ) { 
    this.create_recipe_form = formBuilder.group({
      name: ["", Validators.required],
      description: ["", Validators.required],
      image_id: ''

    });
  }

  ngOnInit() {

  }

  createRecipe(): void {
    this._recipeService.createRecipe(this.create_recipe_form.value)
      .subscribe(
        recipe => {
          console.log(recipe);
          this.readRecipes();
        },
        error => console.log(error)
      );
  } 

  readRecipes(): void {
    this.show_read_recipes_event.emit({ title: "Read Recipes" });
  }

  uploadImage(e) {
    let files = this.elem.nativeElement.querySelector('#selectFile').files;
    let formData = new FormData();
    let file = files[0];

    formData.append('selectFile', file, file.name);

    this._imageService.uploadImage(formData)
      .subscribe(
        image => {
          console.log(image);
          this.addImageIdToHtml(image)

          e.preventDefault();
          e.stopPropagation();
        },
        error => console.log(error)
      );
  }

  addImageIdToHtml(image){
    this.imageId = image[0];
    $("#image_id").val(this.imageId);
    $("#image_id").text(this.imageId);
  }

}

1 个答案:

答案 0 :(得分:1)

jQuery直接操作DOM,但在Angular形式的情况下,您创建并销毁表单实例,修改DOM并不一定意味着更改表单实例值。我建议你使用Angular自己的函数来管理表单值的变化。尝试将addImageIdToHtml更改为以下内容:

addImageIdToHtml(image){
    this.imageId = image[0];
    this.create_recipe_form.patchValue( {
        "image_id" : this.imageId
    } );
}