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



我设计了一个Angular 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>

我的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);
  }
}

jQuery直接操纵DOM,但是在角度形式的情况下,您可以创建和破坏式式实例,并修改DOM并不一定意味着更改form实例值。我建议您使用Angular自己的功能来管理形式的价值更改。尝试将您的AddimageIdToHtml更改为以下内容:

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

最新更新