【问题标题】:How to get select option in Angular2如何在Angular2中获得选择选项
【发布时间】:2020-04-03 19:19:01
【问题描述】:

用 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>

在控制台我得到

【问题讨论】:

  • 什么是表单值?类别选项是否为空?只需登录this.addRecipeForm.value 我也无法在您的 js 文件中看到类别。 ngMolde 正在尝试绑定到那个
  • 我添加了更多代码..

标签: angular asp.net-core-mvc


【解决方案1】:

你几乎拥有它。 NgModel 将 select 表单元素的值绑定到一个变量。

这里我把它绑定到组件的addRecipeForm.category属性键上:

<div class="form-group">
  <label for="category">Category</label>
  <select [(ngModel)]="addRecipeForm.category">
    <option *ngFor="let category of categories">{{category.name}}</option>
  </select>
</div>

您可以使用this.addRecipeForm.category 在代码中访问它。

【讨论】:

  • 仍然无法正常工作..我更新了问题并添加了更多详细信息的代码..
【解决方案2】:

您的代码理解起来有点复杂,缺少部分内容,例如我想您也在 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
  }

我的英语不太好,对不起

来自智利的问候

【讨论】:

  • @BartolV9 你能把你所有的html和ts代码贴出来吗?
  • 我发现了问题,在你HTML的第55、56、61行,正如我之前告诉你的,字段必须与你在表单中定义的名称相同,你必须将addRecipeForm.get('category').替换为@987654325 @ 因为您在 categoryId 这样的表单中以这种方式定义了它,所以您还必须将 select 元素的 formControlName(HTML 第 57 行)更改为 formControlName="categoryId" 我希望对您有所帮助。 (对不起我的英语)问候
【解决方案3】:

我确实找到了解决方案!

我不得不为此更改一些代码:

<div class="form-group">
          <label for="categoryId">Category</label>
          <select class="form-control" formControlName="categoryId">
              <option *ngFor="let category of categories" [value]="category.id">{{category.name}}</option>
          </select>
          <div class="invalid-feedback"
        *ngIf="addRecipeForm.get('categoryId').touched && addRecipeForm.get('categoryId').hasError('required')"> You must select category
          </div>
      </div>

感谢您的回答!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    相关资源
    最近更新 更多