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. onvif开发总结

    ONVIF开发经验总结 ONVIF开发经验总结............................................................................. ...

  2. Repeater控件的

    http://blog.csdn.net/zhang_xinxiu/article/details/21872433 想起来,公司的aspx页面前台数据展示除了datagrid以为还有Repeater ...

  3. netstat---显示Linux中网络系统的状态信息

    netstat命令用来打印Linux中网络系统的状态信息,可让你得知整个Linux系统的网络情况. 语法 netstat(选项) 选项 -a或--all:显示所有连线中的Socket: -A<网 ...

  4. iptables---linux防火墙

    iptables命令是Linux上常用的防火墙软件,是netfilter项目的一部分.可以直接配置,也可以通过许多前端和图形界面配置. 语法 iptables(选项)(参数) 选项 -t<表&g ...

  5. Install Docker Mac OS X

    检查 Mac OS version 要求必须是 OS X 10.6 Snow Leopard or newer to run Boot2Docker 安装 Boot2Docker 列表内容 下载地址: ...

  6. erlang虚拟机代码运行原理

    erlang是开源的,非常多人都研究过源码.可是.从erlang代码到c代码.这是个不小的跨度.并且代码也比較复杂. 所以这里,我利用一些时间,整理下erlang代码的运行过程.从erlang代码编译 ...

  7. 快速排序的期望复杂度O(nlogn)证明。

    快速排序的最优时间复杂度是 \(O(nlogn)\),最差时间复杂度是 \(O(n^2)\),期望时间复杂度是 \(O(nlogn)\). 这里我们证明一下快排的期望时间复杂度. 设 \(T(n)\) ...

  8. EPC-9600I-L开发板使用

    1,开发板屏幕,先买的开发板,再买的屏幕,屏幕是7英寸的,与开发板默认烧进的内核不匹配,找板商重新要了匹配的内核,将原内核替换掉,根文件系统和uboot不变,进行重烧. 2,开发板屏幕校准准备 如果校 ...

  9. React项目编译node内存溢出

    坑爹的node 内存溢出 react开发项目  安装一个插件依赖 ,然后就报错了 报错如下(自己的没有截图出来 这是从别人的截图---报错基本差不多) 之前因为项目大而且旧的原因  使用 过      ...

  10. BZOJ1023: [SHOI2008]cactus仙人掌图(仙人掌)

    Description 如果某个无向连通图的任意一条边至多只出现在一条简单回路(simple cycle)里,我们就称这张图为仙人掌图(cactus).所谓简单回路就是指在图上不重复经过任何一个顶点的 ...