嗨,我正在开发一个 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
)
{}
}
希望有人能让我摆脱痛苦(我已经坚持了几天了)。