[Angular] Update FormArray with patchValue
Currently, patchValue doesn't support update FormArray.
The workarround is you need to empty the form array first, then add items back.
import {ChangeDetectionStrategy, Component, EventEmitter, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
import {FormBuilder, FormArray, FormGroup, FormControl, Validators} from '@angular/forms';
import {Meal} from '../../../shared/services/meals/meals.service';
@Component({
selector: 'meal-form',
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrls: ['meal-form.component.scss'],
template: `
<div class="meal-form">
<form [formGroup]="form">
<div class="meal-form__name">
<label>
<h3>Meal name</h3>
<input type="text"
formControlName="name"
placeholder="e.g. English Breakfast">
<div class="error" *ngIf="required">
Workout name is required
</div>
</label>
</div>
<div class="meal-form__food">
<div class="meal-form__subtitle">
<h3>Food</h3>
<button
type="button"
(click)="addIngredient()"
class="meal-form__add">
<img src="/img/add-white.svg" alt="Add food">
Add food
</button>
</div>
<div formArrayName="ingredients">
<label *ngFor="let c of ingredients.controls; index as i;">
<input type="text" [formControlName]="i" placeholder="e.g Eggs">
<span
class="meal-form__remove"
(click)="removeIngredient(i)"
></span>
</label>
</div>
<div class="meal-form__submit">
<div>
<button
*ngIf="!exists"
type="button" class="button" (click)="createMeal()">
Create Meal
</button>
<button
*ngIf="exists"
type="button" class="button" (click)="updateMeal()">
Save
</button>
<a
[routerLink]="['../']"
class="button button--cancel">
Cancel
</a>
</div>
<div class="meal-form__delete" *ngIf="exists">
<div *ngIf="toggled">
<p>Delete item?</p>
<button
class="confirm"
type="button"
(click)="removeMeal()">
Yes
</button>
<button
class="cancel"
type="button"
(click)="toggle()">
No
</button>
</div>
<button
class="button button--delete"
type="button"
(click)="toggle()">
Delete
</button>
</div>
</div>
</div>
</form>
</div>
`
})
export class MealFormComponent implements OnChanges {
toggled = false;
exists = false;
@Input()
meal: Meal;
@Output()
create = new EventEmitter<Meal>();
@Output()
update = new EventEmitter<Meal>();
@Output()
remove = new EventEmitter<Meal>();
form = this.fb.group({
name: ['', Validators.required],
ingredients: this.fb.array([''])
});
get ingredients() {
// Type check for ingredients, mark as FormArray
// Therefore when we use 'ingredients',
// We can get auto complete
return this.form.get('ingredients') as FormArray;
}
get required() {
return (
this.form.get('name').hasError('required') &&
this.form.get('name').touched
);
}
constructor(private fb: FormBuilder) {
}
ngOnChanges(changes: SimpleChanges): void {
if (this.meal && this.meal.name) {
this.exists = true;
this.emptyIngredients();
const value = this.meal;
this.form.patchValue(value);
if (value.ingredients) {
for (const item of value.ingredients) {
this.ingredients.push(new FormControl(item));
}
}
}
}
emptyIngredients() {
while (this.ingredients.controls.length > ) {
this.ingredients.removeAt();
}
}
createMeal() {
if (this.form.valid) {
this.create.emit(this.form.value);
}
}
updateMeal() {
if (this.form.valid) {
this.update.emit(this.form.value);
}
}
removeMeal() {
this.remove.emit(this.form.value);
}
addIngredient() {
// Add a new FormControl to FormArray
this.ingredients.push(new FormControl(''));
}
removeIngredient(i: number) {
this.ingredients.removeAt(i);
}
toggle() {
this.toggled = !this.toggled;
}
}
[Angular] Update FormArray with patchValue的更多相关文章
- Angular 4+ 修仙之路
Angular 4.x 快速入门 Angular 4 快速入门 涉及 Angular 简介.环境搭建.插件表达式.自定义组件.表单模块.Http 模块等 Angular 4 基础教程 涉及 Angul ...
- Node.js && Angular && TypeScript 环境安装与更新
安装 Node.js 下载并安装Node.js Angular 执行命令 npm install -g @angular/cli 参考资料: angular quickstart TypeScript ...
- Speeding up AngularJS apps with simple optimizations
AngularJS is a huge framework with that already has many performance enhancements built in, but they ...
- Angular4.0.0发布总览文章
翻译自angular.io上的关于4.0.0版本发布的文章,内容主要是介绍了4.0.0版本下的改进以及接下来还会有的其他更新,4.0.0其实已经出来好多天了,截止目前都已经到了4.0.1版本了,这也是 ...
- 记录项目版本升级angular4 ~ angular5
前言: 在上一篇ng4文章<angular4--实际项目搭建总结>中说过,等到ng5正式发布,并且蚂蚁的NG ZORRO兼容ng5之后,我会对ng4项目进行升级.这篇文章就是大概说下升级的 ...
- Angular5的new feature
https://blog.angular.io/version-5-0-0-of-angular-now-available-37e414935ced Version 5.0.0 of Angular ...
- Angular4.0.0正式发布,附新特性及升级指南
本文首发地址:Angular4.0.0正式发布,附新特性及升级指南 作者|孙薇 编辑|尾尾 经历了6个RC版本之后,Angular项目组终于发布了新版,即正式版 Angular 4.0.0.新版的 A ...
- [Angular] Working with FormArray
'FormArray' can work with array of 'FormGroup' or 'FormControl'. form = new FormGroup({ stock: new F ...
- Angular 从入坑到挖坑 - 表单控件概览
一.Overview angular 入坑记录的笔记第三篇,介绍 angular 中表单控件的相关概念,了解如何在 angular 中创建一个表单,以及如何针对表单控件进行数据校验. 对应官方文档地址 ...
随机推荐
- ES6学习笔记(八)第七种类型Symbol
1.概述 ES5 的对象属性名都是字符串,这容易造成属性名的冲突.比如,你使用了一个他人提供的对象,但又想为这个对象添加新的方法(mixin 模式),新方法的名字就有可能与现有方法产生冲突.如果有一种 ...
- 干货分享 -- Math
昼猫笔记 JavaScript -- Math Math也是JS的内置对象,但是它不是一个构造函数,它属于一个工具类不用创建对象,它封装了数学运算相关的属性和方法,今天就来写下常用的函数[API(ap ...
- pythong中的全局变量的调用和嵌套函数中变量的使用
全局变量调用:想要在自定义的函数中使用全局变量,就得要在函数用关键字global声明,然后就可以对全局变量进行修改.嵌套函数中的变量的调用:要在嵌套的变量中,使用nonlocal的声明'''num = ...
- Activiti工作流框架学习(二)——使用Activiti提供的API完成流程操作
可以在项目中加入log4j,将logj4.properties文件拷入到src目录下,这样框架执行的sql就可以输出到到控制台,log4j提供的日志级别有以下几种: Fatal error war ...
- 洛谷 P3486 [POI2009]KON-Ticket Inspector
P3486 [POI2009]KON-Ticket Inspector 题目描述 Byteasar works as a ticket inspector in a Byteotian Nationa ...
- tcp_tw_recycle检查tcp_timestamps的内核代码
注意:本文档中的内核代码的版本号:linux-4.0.5 /************************************************* * Author : Samson * ...
- vue methods 方法中 方法 调用 另一个方法。
vue在同一个组件内: methods中的一个方法调用methods中的另外一个方法. 可以在调用的时候 this.$options.methods.test(); this.$options.met ...
- 小的时候.by小雷
小的时候,总是有很多想法. 想去做,却做不成. 因为,自己小,被父母约束着,被学校圈着,被老师教育着. 想买个小霸王游戏机,没钱.在父辈的眼中,"游戏" ,游戏室,电脑游戏 ...
- 【Codeforces Round #456 (Div. 2) A】Tricky Alchemy
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 统计需要的个数. 不够了,就买. [代码] #include <bits/stdc++.h> #define ll lo ...
- STL_算法_查找算法(search、find_end)
C++ Primer 学习中. .. 简单记录下我的学习过程 (代码为主) search //从左往右找第一个符合条件的子区间 全部容器适用 find_end //从右往左找 ...