[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 ...
随机推荐
- 缓存函数memorize
function mulity(x){ return x*x; } function memorize(f){ var cache = {}; var key = arguments.length + ...
- POJ 2227 FloodFill (priority_queue)
题意: 思路: 搞一个priority_queue 先把边界加进去 不断取最小的 向中间扩散 //By SiriusRen #include <queue> #include <cs ...
- [ Java ] [ Spring ] Spring 一些配置项 及 <context:annotation-config/> 專文解释说明
節錄重點: @ Resource .@ PostConstruct.@ PreDestro.@PersistenceContext.@Required 都必須聲明相關的 bean 所以如果總是需要按照 ...
- iptables-save && iptables-restore iptables规则保存于还原
iptables-save命令用于将linux内核中的iptables表导出到标准输出设备商,通常,使用shell中I/O重定向功能将其输出保存到指定文件中. 语法 -t:指定要保存的表的名称. 实例 ...
- idea git ignore 插件
https://blog.csdn.net/qq_34590097/article/details/56284935
- HDU1050:Moving Tables
pid=1050">Moving Tables Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 ...
- iPad之Linux平台实践
updata.... 本文出自 "李晨光原创技术博客" 博客,谢绝转载!
- HDU 2988 Dark roads(kruskal模板题)
Dark roads Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total ...
- windows 静态和动态库
c++中共有两种库:1.动态链接库LIB包含了函数所在的DLL文件和文件中函数位置的信息(入口),代码由运行时加载在进程空间中的DLL提供,称为动态链接库dynamic link library.(这 ...
- jQ-多选按钮实现单选按钮的功能以及input按钮的优化
css: .displayN{display: none;} label {font-size:12px;cursor:pointer;} label i {font-size:12px;font-s ...