首页 > 解决方案 > 如何在Angular2中获得选择选项

问题描述

用 ASP.Net Core MVC + Angular 编写我正在尝试添加新配方,但我只有从选择选项中获取价值时遇到问题。当我添加没有类别的新食谱时,一切都很好。我正在使用响应式表单进行验证。

我的课程:

export interface Category {
    id: number;
    name: string;
    recipes?: Recipe[];
}
export interface Recipe {
    id: number;
    name: string;
    ingredients: string;
    preparationTime: number;
    dateAdded: Date;
    photoUrl: string;
    description?: string;
    recipePhotos?: RecipePhoto[];
}

在我的 add-recipe.component.ts

export class AddRecipeComponent implements OnInit {
  categories: Category[];
  user: User;
  recipe: Recipe;
  addRecipeForm: FormGroup;
  constructor(private fb: FormBuilder,
              private alertifyService: AlertifyService,
              private router: Router,
              private recipeService: RecipeService, private authService: AuthService) { }

  ngOnInit() {
    this.createRecipeForm();
    this.getCategories();
  }


  createRecipeForm() {
    this.addRecipeForm = this.fb.group({
      name: ['', Validators.required],
      ingredients: ['', Validators.required],
      preparationTime: ['', Validators.required],
      description: ['', Validators.required],
      categoryId: ['', Validators.required]
    });
  }


  createRecipe(id: number) {
    if (this.addRecipeForm.valid) {
      this.recipe = Object.assign({}, this.addRecipeForm.value);
      this.recipeService.addNewRecipe(this.authService.currentUser.id, this.recipe).subscribe(() => {
        this.alertifyService.success('New recipe has been added!');
      }, error => {
        this.alertifyService.error(error);
      }, () => {
          this.router.navigate(['/recipes']);
        });
    }
  }


  cancel() {
    this.router.navigate(['members']);
    this.alertifyService.warning('Cancelled');
  }

  getCategories() {
    this.recipeService.getCategories().subscribe(response => {
      this.categories = response;
    }, error => {
      this.alertifyService.error(error);
    })
  }

}

在我的 HTML

<div class="container" >
  <div class="row justify-content-center">
    <div class="col-lg body-card-shadow">
      <form [formGroup]="addRecipeForm" class="p-5" 
      (ngSubmit)="createRecipe()">
        <h2 class="text-center text-primary"> ADD NEW RECIPE</h2>
        <hr>

        <div class="form-group">
          <input type="text" [ngClass]="{
              'is-invalid':
                addRecipeForm.get('name').errors &&
                addRecipeForm.get('name').touched
            }" class="form-control" formControlName="name" placeholder="Name" />
          <div class="invalid-feedback">Please name your Recipe</div>
        </div>

        <div class="form-group">
          <input type="text" [ngClass]="{
              'is-invalid':
                addRecipeForm.get('ingredients').errors &&
                addRecipeForm.get('ingredients').touched
            }" class="form-control" formControlName="ingredients" placeholder="Ingredients.." />
          <div class="invalid-feedback"
          *ngIf="addRecipeForm.get('ingredients').touched && addRecipeForm.get('ingredients').hasError('required')"> Ingredients are required
        </div>
        </div>

        <div class="form-group">
          <input type="number" [ngClass]="{
              'is-invalid':
                addRecipeForm.get('preparationTime').errors &&
                addRecipeForm.get('preparationTime').touched
            }" class="form-control" formControlName="preparationTime" placeholder="Preparation Time" />
          <div class="invalid-feedback"
          *ngIf="addRecipeForm.get('preparationTime').touched && addRecipeForm.get('preparationTime').hasError('required')"> Preparation Time is required
        </div>
        </div>

        <div class="form-group">
          <textarea cols=100% rows="6" [ngClass]="{
              'is-invalid':
                addRecipeForm.get('description').errors &&
                addRecipeForm.get('description').touched
            }" class="form-control" formControlName="description" placeholder="Description"></textarea>
          <div class="invalid-feedback"
          *ngIf="addRecipeForm.get('description').touched && addRecipeForm.get('description').hasError('required')"> Descripe your recipe, it's important!
        </div>
        </div>

        <div class="form-group">
          <label for="category">Category</label>
          <select [ngClass]="{
            'is-invalid':
              addRecipeForm.get('category').errors &&
              addRecipeForm.get('category').touched
          }"  class="form-control" formControlName="category">
              <option *ngFor="let category of categories">{{category.name}}</option>
          </select>
          <div class="invalid-feedback"
        *ngIf="addRecipeForm.get('category').touched && addRecipeForm.get('category').hasError('required')"> You must select category
      </div>
      </div>
        <div class="form-group text-center">
          <button class="btn btn-success" [disabled]="!addRecipeForm.valid" type="submit">Add</button>
          <button class="btn btn-default" type="button" (click)="cancel()">
            Cancel
          </button>
        </div>

      </form>
    </div>
  </div>
</div>

在控制台中我得到在此处输入图像描述

标签: angularasp.net-core-mvc

解决方案


您的代码理解起来有点复杂,缺少部分,例如我想您也加载到 ngOnInit() 中的类别列表

您正在使用 reactiveForm 来定义表单,并且必须使用 reactiveForm 来捕获值字段

文档在这里:https ://angular.io/guide/reactive-forms

您只需修改 html 以定义字段名称,表单元素必须使用 formControlName 定义,其名称与您在 this.addRecipeForm 中分配的名称相同

<form [formGroup]="addRecipeForm" (ngSubmit)="createRecipe()">

<!-- others fields should be here --> 
<div class="form-group">
    <label for="categorxy">Category</label>
    <select formControlName="category">
        <option *ngFor="let category of categories">{{category.name}}</option>
    </select>
</div>

<form>

提交功能

  createRecipe() {
    if (this.addRecipeForm.invalid) { return; }

      const valuesForm = this.addRecipeForm.value
      // valuesForm.category

      // Here call service save Recipe
  }

我英语不太好,对不起

来自智利的问候


推荐阅读