It it recommeded that when deals with form component, we can create a container component to hold state, and then create a stateless component to enpower the form.

For example:

In the example has two components, one is container component 'meal.component.ts', another is statless component 'meal-form.component.ts'.

For the container component, it talks to service:

import {Component} from '@angular/core';
import {Meal} from '../../../shared/services/meals/meals.service';
@Component({
selector: 'meal',
styleUrls: ['meal.component.scss'],
template: `
<div class="meal">
<div class="meal__title">
<h1>
<img src="/img/food.svg" alt="Food">
<span>Create meal</span>
</h1>
</div>
<div>
<meal-form
(create)="addMeal($event)"
></meal-form>
</div>
</div>
`
})
export class MealComponent {
constructor() { } addMeal(meal: Meal) {
console.log("meal", JSON.stringify(meal, null, 2))
}
}

So 'addMeal' function will dispatch action to talk to the service.

For statless component:

import {ChangeDetectionStrategy, Component, EventEmitter, Output} 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> <div class="meal-form__submit">
<div>
<button type="button" class="button" (click)="createMeal()">
Create Meal
</button>
<a
[routerLink]="['../']"
class="button button--cancel">
Cancel
</a>
</div>
</div>
</form>
</div>
`
})
export class MealFormComponent { @Output()
create = 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) { } createMeal() {
if (this.form.valid) {
this.create.emit(this.form.value);
}
} addIngredient() {
// Add a new FormControl to FormArray
this.ingredients.push(new FormControl(''));
} removeIngredient(i: number) {
this.ingredients.removeAt(i);
}
}

It uses ReactiveForm to create form.

Things to be notice:

1. Add type check for form 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;
}

Then whenever you use 'this.ingredients', it will show auto complete.

2. FormArray method:

  addIngredient() {
// Add a new FormControl to FormArray
this.ingredients.push(new FormControl(''));
} removeIngredient(i: number) {
this.ingredients.removeAt(i);
}

[Angular] Component architecture and Reactive Forms的更多相关文章

  1. Angular Reactive Forms -- Model-Driven Forms响应式表单

    Angular 4.x 中有两种表单: Template-Driven Forms - 模板驱动式表单 (类似于 AngularJS 1.x 中的表单 )  官方文档:https://v2.angul ...

  2. [Angular] Create a custom validator for reactive forms in Angular

    Also check: directive for form validation User input validation is a core part of creating proper HT ...

  3. Angular开发实践(三):剖析Angular Component

    Web Component 在介绍Angular Component之前,我们先简单了解下W3C Web Components 定义 W3C为统一组件化标准方式,提出Web Component的标准. ...

  4. Angular之响应式表单 ( Reactive Forms )

    项目结构 一 首页 ( index.html ) <!doctype html> <html lang="en"> <head> <met ...

  5. ng2响应式表单-翻译与概括官网REACTIVE FORMS页面

    本文将半翻译半总结的讲讲ng2官网的另一个未翻译高级教程页面. 原文地址. 文章目的是使用ng2提供的响应式表单技术快速搭出功能完善丰富的界面表单组件. 响应式表单是一项响应式风格的ng2技术,本文将 ...

  6. Angular2响应式表单-翻译与概括官网REACTIVE FORMS页面

    本文将半翻译半总结的讲讲ng2官网的另一个未翻译高级教程页面. 原文地址. 文章目的是使用ng2提供的响应式表单技术快速搭出功能完善丰富的界面表单组件. 响应式表单是一项响应式风格的ng2技术,本文将 ...

  7. Angular 2 Architecture Overview

    Module 简单来说模块(module)就是完成共同目的的代码块,export一些内容例如一个类.函数.或值变量. component就是一个基本的Angular块,一个component类其实也是 ...

  8. [Angular] Refactor Angular Component State Logic into Directives

    Allow the base toggle to be a tag (<toggle>) or attribute (<div toggle>). The <toggle ...

  9. [Angular] Component's dependency injection

    An Angular service registered on the NgModule is globally visible on the entire application. Moreove ...

随机推荐

  1. Spark 性能相关參数配置具体解释-任务调度篇

    作者:刘旭晖 Raymond 转载请注明出处 Email:colorant at 163.com BLOG:http://blog.csdn.net/colorant/ 随着Spark的逐渐成熟完好, ...

  2. 【Struts2】Struts2纯手工安装、配置以及Helloworld,以最新版struts 2.3.20 GA做样例

    很多网上的教程对Struts2的配置.安装弄得不明不白,非常多高手以为小白是什么都懂.很多细节上面的地方没有说明清楚,甚至还有在Maven上面解说的,要知道Struts2跟Maven没有半点的关系.全 ...

  3. 视图中使用ROWNUM要注意

    昨天晚上帮一位兄弟优化一个ebs的sql. sql有好几百行. SQL的样子是select .... from 视图 where ....过滤条件 视图的代码贴出来就不给大家看了,比較长.另外设计保密 ...

  4. Socket编程中的强制关闭与优雅关闭及相关socket选项

    以下描述主要是针对windows平台下的TCP socket而言. 首先需要区分一下关闭socket和关闭TCP连接的区别,关闭TCP连接是指TCP协议层的东西,就是两个TCP端之间交换了一些协议包( ...

  5. Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart). Attachment support is disa

    转自:https://blog.csdn.net/ouyangtianhan/article/details/6797999 Unable to find required classes (java ...

  6. JDK版本切换批处理脚本

    我们经常在开发是遇到jdk版本切换的问题 1.手动去修改JAVA_HOME环境变量,将变量的值指向对应的JDK版本的安装目录即可. 2.通过编写批处理脚本来根据选择的JDK版本动态修改JAVA_HOM ...

  7. 最大子矩阵和 51Nod 1051 模板题

    一个M*N的矩阵,找到此矩阵的一个子矩阵,并且这个子矩阵的元素的和是最大的,输出这个最大的值. 例如:3*3的矩阵:   -1 3 -1 2 -1 3 -3 1 2   和最大的子矩阵是:   3 - ...

  8. LuoguP2764 最小路径覆盖问题(最大流)

    题目描述 «问题描述: 给定有向图G=(V,E).设P 是G 的一个简单路(顶点不相交)的集合.如果V 中每个顶点恰好在P 的一条路上,则称P是G 的一个路径覆盖.P 中路径可以从V 的任何一个顶点开 ...

  9. 洛谷 P1405 苦恼的小明

    P1405 苦恼的小明 题目描述 黄小明和他的合伙人想要创办一所英语培训机构,注册的时候要填一张个人情况的表格,在身高一栏小明犯了愁. 身高要求精确到厘米,但小明实在太高了,无法在纸上填下这么长的数字 ...

  10. .Net中的缓存依赖配置

    缓存--能非常好的提高网站的性能. 在訪问量大,但更新较少的站点中使用缓存,能够大大提高执行效率. 在.net中给我们提供了非常好的缓存机制.页面缓存.数据缓存,还有非常好的依赖缓存. 依赖缓存优点就 ...