0

嗨,我正在开发一个 Angular 4 Web 应用程序。我正在尝试设置下拉菜单的初始选定状态。尽管没有设置下拉菜单的初始选定状态,但无论我做什么。请参阅下面的 html(我正在尝试将食谱的健康选项设置为“是”或“否”,具体取决于从数据库中返回的内容:-

<div class="row">
    <div class="col-md-12">
      <form [formGroup]="update_recipe_form" (ngSubmit)="createUpdateRecipeIngredientsDetailsForm()">
        <table class="table table-hover table-responsive table-bordered">

          <tr>
            <td>
              Healthy
            </td>
            <td><!--<li *ngIf="recipe?.healthy == 'Yes'"><h4><i class='fa fa-heart' aria-hidden='true'></i>Healthy</h4></li>-->
              <select name="isHealthy" formControlName="isHealthy" class="form-control" required>
                <option *ngFor="let healthy of healthyOptionsArray" [selected]="isHealthy==healthy.state" value="{{healthy.id}}">
                  {{healthy.state}}
                </option>
              </select>
              <div *ngIf="update_recipe_form.get('isHealthy').touched && update_recipe_form.get('isHealthy').hasError('required')"
                  class="alert alert-danger">Select whether recipe is healthy
              </div>
            </td>
          </tr>

          <tr>
            <td></td>
            <td>
              <button class="btn btn-primary" type="submit" [disabled]="update_recipe_form.invalid">
                  <span class="glyphicon glyphicon-edit"></span> Update
              </button>
            </td>
          </tr>
        </table>
      </form>
    </div>
  </div>

打字稿模块代码:-

import { Component, Output, Input, EventEmitter, OnChanges, ElementRef } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';

import { RecipeService } from '../recipe.service';

import { Recipe } from '../recipe';
import { Healthy } from '../healthy';

@Component({
  selector: 'app-update-recipe',
  templateUrl: './update-recipe.component.html',
  styleUrls: ['./update-recipe.component.css'],
  providers: [RecipeService, CategoryService, DifficultyService, ImageService, IngredientService, IngredientDetailService ]
})
export class UpdateRecipeComponent {

  @Output() show_read_recipes_event = new EventEmitter();

  @Input() recipe_id;

  update_recipe_form: FormGroup;

   healthyOptionsArray = [
    new Healthy(0, 'no'),
    new Healthy(1, 'yes')
  ]

  constructor(private _recipeService: RecipeService, 
              private formBuilder: FormBuilder,
              private elem: ElementRef
  )         
  { 
    // build angular form
    this.update_recipe_form = this.formBuilder.group({
      recipe_name: ["", Validators.required],
      recipe_id: '',
      isHealthy: ["", Validators.required],
    });
  }

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

  ngOnChanges(){
    this._recipeService.readOneRecipeForUpdate(this.recipe_id)
      .subscribe(
        recipe => {
          console.log(recipe);
          this.update_recipe_form.patchValue({
            recipe_name: recipe.recipe_name,
            recipe_id: recipe.recipe_id,
            isHealthy: recipe.healthy,
          });
        }
      );
  }

这是健康类代码:-

export class Healthy{
    constructor(
        public id: number,
        public state: string
    )
    {}
}

希望有人能让我摆脱痛苦(我已经坚持了几天了)。

4

3 回答 3

1

你可以改变:

[selected]="isHealthy==healthy.state"

至:

[selected]="healthy.state === 'yes'"
于 2018-03-03T14:49:51.657 回答
1

healthy如果您设置的对象值与迭代器对象的值完全相同,则使用ngValue指令将整个对象值绑定到表单。这将有助于预先填充价值。

<select name="isHealthy" formControlName="isHealthy" class="form-control" required>
  <option *ngFor="let healthy of healthyOptionsArray" [ngValue]="healthy">
      {{healthy.state}}
   </option>
</select>
于 2018-03-03T14:50:12.483 回答
0

这有效:

<select name="isHealthy" formControlName="isHealthy" class="form-control" required>
  <option *ngFor="let healthy of healthyOptionsArray" [selected]="healthy.state == isHealthy">
    {{healthy.state}}
   </option>
 </select>       
于 2018-03-04T09:15:06.557 回答