[Angular] Component architecture and Reactive Forms
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的更多相关文章
- Angular Reactive Forms -- Model-Driven Forms响应式表单
Angular 4.x 中有两种表单: Template-Driven Forms - 模板驱动式表单 (类似于 AngularJS 1.x 中的表单 ) 官方文档:https://v2.angul ...
- [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 ...
- Angular开发实践(三):剖析Angular Component
Web Component 在介绍Angular Component之前,我们先简单了解下W3C Web Components 定义 W3C为统一组件化标准方式,提出Web Component的标准. ...
- Angular之响应式表单 ( Reactive Forms )
项目结构 一 首页 ( index.html ) <!doctype html> <html lang="en"> <head> <met ...
- ng2响应式表单-翻译与概括官网REACTIVE FORMS页面
本文将半翻译半总结的讲讲ng2官网的另一个未翻译高级教程页面. 原文地址. 文章目的是使用ng2提供的响应式表单技术快速搭出功能完善丰富的界面表单组件. 响应式表单是一项响应式风格的ng2技术,本文将 ...
- Angular2响应式表单-翻译与概括官网REACTIVE FORMS页面
本文将半翻译半总结的讲讲ng2官网的另一个未翻译高级教程页面. 原文地址. 文章目的是使用ng2提供的响应式表单技术快速搭出功能完善丰富的界面表单组件. 响应式表单是一项响应式风格的ng2技术,本文将 ...
- Angular 2 Architecture Overview
Module 简单来说模块(module)就是完成共同目的的代码块,export一些内容例如一个类.函数.或值变量. component就是一个基本的Angular块,一个component类其实也是 ...
- [Angular] Refactor Angular Component State Logic into Directives
Allow the base toggle to be a tag (<toggle>) or attribute (<div toggle>). The <toggle ...
- [Angular] Component's dependency injection
An Angular service registered on the NgModule is globally visible on the entire application. Moreove ...
随机推荐
- amlogic M8操作gpio bank
參照规格书: r代表:读 a代表GPIOAO bank 0x28代表read bit echo r a 0x28 > /sys/class/amlogic/debug 操作GPIO口读取 w代表 ...
- vim 基础学习之重复
重复命令 .: 这个命令可以重复之前的操作.例如你执行了dd操作,然后. 就会删除当前行还有从进入插入模式到退出插入模式,之间的修改也算是一次操作.比如,你执行了i aaa <Esc>然后 ...
- android--动态加载、插件化
需求驱动 随着业务发展需要和无线部门的拆分,各业务产品模块归属到各业务BU,原有无线App开发团队被分为基础框架.业务A.业务B.业务C等多个开发团队,从此App的开发和发布进入了一个全新模式.在这种 ...
- 浏览器(BOM)对象的一些内置方法总结
浏览器(BOM)对象的一些内置方法总结 一.总结 1.bom就是浏览器那端执行的代码,dom就是服务器那端操作html的代码 2.记好bom的几个对象,那就很好理解很多代码了,也很好写很多代码了 二. ...
- xshell --- 查看和关闭 进程
netstat -apn | grep 80 kill -l PID 关闭进程
- python stomp activemq客户端
#coding=utf-8import timeimport sysimport stomp class MyListener(object): def on_error(self, headers, ...
- host---域名查询
host命令是常用的分析域名查询工具,可以用来测试域名系统工作是否正常. 选项 -a:显示详细的DNS信息: -c<类型>:指定查询类型,默认值为“IN“: -C:查询指定主机的完整的SO ...
- CMDB学习之五服务端api
服务端api 对发送来的数据进行处理,并返回结果,首先要创建一个Django项目 第一步,就是写URL路由在分支中写url api 主路由 from django.conf.urls import u ...
- 【习题 8-1 UVA - 1149】Bin Packing
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 每个背包只能装两个东西. 而且每个东西都要被装进去. 那么我们随意考虑某个物品.(不必要求顺序 这个物品肯定要放进某个背包里面的. ...
- Mindjet MindManager 思维导图软件-使用思维导图跟踪调用流程,绘制软件框架
思维导图.据说是每一个产品经理必备的软件.假设你阅读大型源码.使用思维导图跟踪调用流程,绘制软件框架将会很方便. 特点:没什么好说的.用过的都说好. 软件截图: 下载:http://www.mindm ...