【发布时间】:2020-06-18 17:06:24
【问题描述】:
我需要为我的表单设置初始值 formArray。 检查我的代码:
HTML:
<div class="form-row form-group ingredients-drop">
<button class="button" (click)="addAlias()">Add ingredients</button>
<label>Kolicina</label>
<div *ngFor="let ingredient of ingredients.controls; let i=index">
<input class="select add-ingredients" type="text" [formControlName]="i">
</div>
</div>
TS:
allRecepies: any[] = [];
selectedMeal: any
form: FormGroup;
ngOnInit() {
this.getAllRecepies();
}
onChange(event) {
this.allRecepies.map(obj => {
if (obj.id == event.target.value) {
this.selectedMeal = Object.assign(obj);
console.log(this.form.value);
}
})
this.editCity();
}
getAllRecepies() {
this.mealService.getRecepies().subscribe(
data => {
this.allRecepies = data;
}
)
}
editCity() {
this.form.patchValue({
name: this.selectedMeal.name ? this.selectedMeal.name : null,
description: this.selectedMeal.description ? this.selectedMeal.description : null,
preparationTime: this.selectedMeal.preparationTime ? this.selectedMeal.preparationTime : null,
pictureUrl: this.selectedMeal.pictureUrl ? this.selectedMeal.pictureUrl : null,
ingredients: this.selectedMeal.ingredients ? this.addMealArr() : null
})
}
addMealArr() {
if(this.selectedMeal) {
let a = this.selectedMeal.ingredients.map(obj => { return obj });
return a;
}
}
createForm() {
this.form = this.formBuilder.group({
name: [null],
description: [null],
preparationTime: [null],
pictureUrl: [''],
ingredients: this.formBuilder.array([
this.formBuilder.control(this.addMealArr())
])
});
}
get ingredients() {
return this.form.get('ingredients') as FormArray;
}
addAlias() {
this.ingredients.push(this.formBuilder.control(''));
}
这可能是不好的做法,但我需要针对我的问题或 stackblitz 的教程,或者有人可以帮助我吗? 如果可能的话,我需要用 patchValue 设置初始值吗? 还是使用其他方法? 我不知道只是给我发教程或更改我的代码或设置 stackblitz? 我需要设置初始值并添加新行或删除现有的..
【问题讨论】:
标签: javascript html angular typescript