[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 中创建一个表单,以及如何针对表单控件进行数据校验. 对应官方文档地址 ...
随机推荐
- tensorflow学习之路-----卷积神经网络个人总结
卷积神经网络大总结(个人理解) 神经网络 1.概念:从功能他们模仿真实数据 2.结构:输入层.隐藏层.输出层.其中隐藏层要有的参数:权重.偏置.激励函数.过拟合 3.功能:能通过模仿,从而学到事件 其 ...
- IDEA集成Python插件,SDK配置
(第一次写在博客园添加随笔, 会有些生硬,有不对的地方和描述错误之处希望可以指出) 最近在学习一个新的知识点,涉及到Python的使用,因为第一次接触很多地方都不是很明白 ,好,废话不多说,现在直接上 ...
- vue 常用ui组件库
vux github ui demo:https://github.com/airyland/vux Mint UI 项目主页:http://mint-ui.github.io/#!/zh-cn de ...
- 【Uva 307】Sticks
[Link]: [Description] 给你最多n个棍子; (n< = 64) 每根棍子长度(1..50) 问你这n根棍子,可以是由多少根长度为x的棍子分割出来的; x要求最小 [Solut ...
- OpenStack_Swift源代码分析——Object-auditor源代码分析(2)
1 Object-aduitor审计详细分析 上一篇文章中,解说了Object-aduitor的启动,当中审计的详细运行是AuditorWorker实现的.在run_audit中实例化了Auditor ...
- [Python] Understand Mutable vs. Immutable objects in Python
In this lesson, you will learn what mutable and immutable objects are, and the difference between th ...
- python调用Java代码,完毕JBPM工作流application
1.缘由 有一庞大Python django webproject,要引入工作流引擎,像OA一样.方便的流程控制与管理.Python或django关于工作流的开源插件,稀少,并且弱爆了,终于选用jav ...
- DB2物化视图(Materialized Query Tables, MQT)
DB2的物化视图MQT是基于查询结果定义的一个表,MQT中包括的数据来自MQT定义所基于的一个或多个表, 使用MQT能够显著提高查询的操作性能. 数据库的视图和MQT都是基于一个查询来定义的.每当视图 ...
- 41.Node.js使用cnpm
转自:http://www.runoob.com/nodejs/nodejs-tutorial.html npm是Node.js中维护第三方库.模块的工具,但是国外的速度很悲剧,这里有一个中国的源cn ...
- Kinect 开发 —— 骨骼追踪 (下)
基于景深数据的用户交互 骨骼数据中关节点不仅有X,Y值,还有一个深度值 除了使用WPF的3D特性外,在布局系统中可以根据深度值来设定可视化元素的尺寸大小来达到某种程序的立体效果. 下面的例子使用Can ...