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. Volley简单学习使用五—— 源代码分析三

    一.Volley工作流程图: 二.Network     在NetworkDispatcher中须要处理的网络请求.由以下进行处理: NetworkResponse networkResponse = ...

  2. STM32的IO口的8种配置

    STM32的IO口的8种配置 1 STM32的输入输出管脚有以下8种可能的配置:(4输入+2输出+2复用输出) ① 浮空输入_IN_FLOATING ② 带上拉输入_IPU ③ 带下拉输入_IPD ④ ...

  3. Android实现QQ分享及注意事项

    一.获取APPID和帮助文档 在前面我介绍了关于Android中微信分享的文章< Android实现微信分享及注意事项>这一篇文章来看看关于QQ分享. 可以参看新手引导和接入说明:http ...

  4. kali之Nmap (Network Mapper(网络映射器)

    Nmap是主机扫描工具,他的图形化界面是Zenmap,分布式框架为Dnamp. Nmap可以完成以下任务: 主机探测 端口扫描 版本检测 系统检测 支持探测脚本的编写 Nmap在实际中应用场合如下: ...

  5. 如何通过使用fiddler对Android系统设备抓包总结

    http://www.open-open.com/lib/view/open1427509907668.html

  6. poj3244(公式题)

    Difference between Triplets Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 2476   Acce ...

  7. FragMent-通过Arguments方法 跟activity通信

    今天主要学习下通过Arguments,实现activity 给fragment传递数据.这个方法也是通过参数bundle来进行数据传输的 直接看如下代码 一,定义一个fragment,在oncreat ...

  8. golang 方法内部定义子方法及调用

    package main import ( "fmt" "reflect" ) func out(ch chan int) { <-ch fmt.Prin ...

  9. BZOJ2806: [Ctsc2012]Cheat(广义后缀自动机,单调队列优化Dp)

    Description Input 第一行两个整数N,M表示待检查的作文数量,和小强的标准作文库的行数接下来M行的01串,表示标准作文库接下来N行的01串,表示N篇作文 Output N行,每行一个整 ...

  10. 八、Docker+RabbitMQ

    原文:八.Docker+RabbitMQ 一.下载镜像 docker pull rabbitmq:management 二.运行 docker run -d --name rabbitmq -e TZ ...