Angular 2 - JQuery 代码设置的表单元素值未与其他手动输入的表单数据一起提交
Angular 2 - Form element value set by JQuery code is not being submitted with other manually entered form data
我设计了一个 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,但在 Angular 表单的情况下,您创建和销毁表单实例,而修改 DOM 不一定意味着更改表单实例值。我建议你使用 Angular 自带的函数来管理表单值的变化。尝试将您的 addImageIdToHtml 更改为以下内容:
addImageIdToHtml(image){
this.imageId = image[0];
this.create_recipe_form.patchValue( {
"image_id" : this.imageId
} );
}
我设计了一个 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,但在 Angular 表单的情况下,您创建和销毁表单实例,而修改 DOM 不一定意味着更改表单实例值。我建议你使用 Angular 自带的函数来管理表单值的变化。尝试将您的 addImageIdToHtml 更改为以下内容:
addImageIdToHtml(image){
this.imageId = image[0];
this.create_recipe_form.patchValue( {
"image_id" : this.imageId
} );
}