[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 ...
随机推荐
- hdu1856 More is better (并查集)
More is better Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 327680/102400 K (Java/Others) ...
- 谈谈 Struts2 的拦截器
套话 相信非常多人都用过 Struts2 了,当然,对 Struts2 的原理也都比較了解.之前在一个项目中就已经用到了,当初的理解也不过局限在应用的层面上,对于更深层次的原理.机制,了解的并非非常多 ...
- JAVA基础针对自己薄弱环节总结02(循环)
循环 A:水仙花. classShuiXianHua { public static void main(String[] args) { for(int i=101;i<1000;i++) { ...
- android图像处理系列之四-- 给图片添加边框(上)
图片处理时,有时需要为图片加一些边框,下面介绍一种为图片添加简单边框的方法. 基本思路是:将边框图片裁剪成八张小图片(图片大小最好一致,不然后面处理会很麻烦),分别对应左上角,左边,左下角,下边,右下 ...
- 37.cgi网页交互
1.Apache的安装 地址:链接:https://pan.baidu.com/s/1kWdSWwZ 密码:nuqo 2.在相应路径下写html如图所示 new.html代码: <html> ...
- Android自定义组件系列【13】——Android自定义对话框如此简单
在我们的日常项目中很多地方会用到对话框,但是Android系统为我们提供的对话框样子和我们精心设计的界面很不协调,在这种情况下我们想很自由的定义对话框,或者有的时候我们的对话框是一个图片,没有标题和按 ...
- Ajax往后台传参数,无参数,一个参数,多个参数,一个对象等
原文:http://www.cnblogs.com/chenwolong/p/Get.html //无参数请求-简单示例 $(document).ready(function () { $.ajax( ...
- LuoguP4012 深海机器人问题(费用流)
题目描述 深海资源考察探险队的潜艇将到达深海的海底进行科学考察. 潜艇内有多个深海机器人.潜艇到达深海海底后,深海机器人将离开潜艇向预定目标移动. 深海机器人在移动中还必须沿途采集海底生物标本.沿途生 ...
- python 补0的方法
# 方法一 z = 'bb' z.zfill(6) ----'0000bb' n = ' n.zfill(5) ----' # 方法二 ' " ---- '报错' # 方法的区别 方法二只能 ...
- Python修改文件内容
工作中要写个脚本来修改文件的内容,然后就写了一个刷子: #coding:utf8 import os def modify_file(old_file, new_version, old_versio ...