Getting started wtih Angular 2: part 4
#Create a new post Since Angular2 RC2 introduced a complete new form modules(search @angular/forms in https://npmjs.com),it allow you use template driven form like Angular 1.x,it also support the programatic approach. In the previous posts,we have create some components,and use HTTP client to fetch data from backend APIs. In this post,we will focus on form submission. Add Postnew-post.component.ts: import { Component,OnInit,OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import { Post } from '../core/post.model'; import { PostService } from '../core/post.service'; @Component({ selector: 'app-new-post',templateUrl: './new-post.component.html',styleUrls: ['./new-post.component.css'] }) export class NewPostComponent implements OnInit,OnDestroy { data = { title: '',home: '' }; sub: Subscription; constructor(private postService: PostService,private router: Router) { } save() { console.log('saving post data!' + this.data); this.postService .savePost(this.data) .subscribe(res => { this.router.navigate(['','posts']); }); } ngOnInit() { } ngOnDestroy() { // if (this.sub) { // this.sub.unsubscribe(); // } } } In the constructor method,it injects Add the following content into new-post.component.html file. <div class="card"> <div class="card-header"> <h1 class="card-title">{{'new-post'}} </h1> <p><small>all fields marked with star are required.</small></p> </div> <div class="card-block"> <form id="form" #f="ngForm" name="form" class="form" (ngSubmit)="save()" novalidate> <div class="form-group" [class.has-danger]="title.invalid && !title.pristine"> <label class="form-control-label" for="title">{{'title'}} *</label> <input class="form-control" id="title" name="title" #title="ngModel" [(ngModel)]="data.title" required/> <div class="form-control-feedback" *ngIf="title.invalid && !title.pristine"> <p *ngIf="title.errors.required">Post Title is required</p> </div> </div> <div class="form-group" [class.has-danger]="home.invalid && !home.pristine"> <label class="form-control-label" for="home">{{'home'}} *</label> <textarea class="form-control" #home="ngModel" type="home" name="home" id="home" [(ngModel)]="data.home" rows="8" required minlength="10"> </textarea> <div class="form-control-feedback" *ngIf="home.invalid && !home.pristine"> <p *ngIf="home.errors.required">Post Home is required</p> <p *ngIf="home.errors.minlength">At least 10 chars</p> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-success btn-lg" [disabled]="f.invalid || f.pending"> {{'save'}}</button> </div> </form> </div> <div class="card-footer"> back to <a [routerLink]="['','posts']">{{'post-list'}}</a> </div> </div>
Similar with AngularJS 1.x,there are some status value can be use for describing the status of form and form fields. such as valid and invalid,dirty and pristine,an form has extra pending and submitted status.
This form uses HTML5 compatible attributes(required,minlength etc) to set form validation,but it use Angular to valdiate. To use form,you have to import ... import { FormsModule } from '@angular/forms'; ... @NgModule({ imports: [ CommonModule,FormsModule,... }) export class PostsModule { } Run this application,navigate to http://localhost:4200. Edit PostSimilar with the New post component. It is easy to complete the edit post page. edit-post.component.ts: import { Component,OnDestroy } from '@angular/core'; import { Router,ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import { Post } from '../core/post.model'; import { PostService } from '../core/post.service'; @Component({ selector: 'app-edit-post',templateUrl: './edit-post.component.html',styleUrls: ['./edit-post.component.css'] }) export class EditPostComponent implements OnInit,OnDestroy { data: Post = { title: '',home: '' }; sub: Subscription; id: number; constructor(private postService: PostService,private router: Router,private route: ActivatedRoute) { } save() { let _body = { title: this.data.title,home: this.data.home }; this.postService .updatePost(this.id,_body) .subscribe(res => this.router.navigate(['','posts'])); } ngOnInit() { this.sub = this.route.params .flatMap(params => { this.id = +params['id']; return this.postService.getPost(this.id); }) .subscribe((res: Post) => this.data = res); } ngOnDestroy() { this.sub.unsubscribe(); } } It is very similar with new-post component,except we fetch the initial post data according to params edit-post.compponent.html: <div class="card"> <div class="card-header"> <h1 class="card-title">{{'edit-post'}} </h1> <p>created at: {{data.createdAt}} ? {{data.createdBy}}</p> <p><small>all fields marked with star are required.</small></p> </div> <div class="card-block"> <form id="form" #f="ngForm" name="form" class="form" (ngSubmit)="save()" novalidate> <div class="form-group" [class.has-danger]="title.invalid && !title.pristine"> <label class="form-control-label" for="title">{{'title'}} *</label> <input class="form-control" id="title" name="title" #title="ngModel" [(ngModel)]="data.title" required/> <div class="form-control-feedback" *ngIf="title.invalid && !title.pristine"> <p *ngIf="title.errors.required">Post Title is required</p> </div> </div> <div class="form-group" [class.has-danger]="home.invalid && !home.pristine"> <label class="form-control-label" for="home">{{'home'}} *</label> <textarea class="form-control" #home="ngModel" type="home" name="home" id="home" [(ngModel)]="data.home" rows="8" required minlength="10"> </textarea> <div class="form-control-feedback" *ngIf="home.invalid && !home.pristine"> <p *ngIf="home.errors.required">Post Home is required</p> <p *ngIf="home.errors.minlength">At least 10 chars</p> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-success btn-lg" [disabled]="f.invalid || f.pending"> {{'save'}}</button> </div> </form> </div> <div class="card-footer"> back to <a [routerLink]="['','posts']">{{'post-list'}}</a> </div> </div> I added extra ReactiveFormsWe have used template driven forms in add ang edit post components,it is stupid and simple and very similar with AnguarJS 1.x. Let have a look at template version of the search bar in posts component. q:string=''; search() { this.sub = this.postService.getPosts({ q: this.q }).subscribe( res => this.posts = res ); } <form class="form-inline"> <div class="form-group" (ngSubmit)="search()"> <input type="text" name="q" class="form-control" [(ngModel)]="q" /> </div> <button type="submit" class="btn btn-outline-info">{{'search'}}</button> </form> In this form,a submit event will trigger <form class="form-inline"> <div class="form-group" (ngSubmit)="search(term.value)"> <input type="text" name="q" class="form-control" #term /> </div> <button type="submit" class="btn btn-outline-info">{{'search'}}</button> </form> search(term:string) { this.sub = this.postService.getPosts({ q: term }).subscribe( res => this.posts = res ); } If you want more interactive when inputing search term and get the result as soon as possible. The simplest way is adding a keyup output binding to <form class="form-inline"> <div class="form-group" (ngSubmit)="search(term.value)"> <input type="text" name="q" class="form-control" #term (keyup)="search(term.value)"/> </div> <button type="submit" class="btn btn-outline-info">{{'search'}}</button> </form> A more controlable approach is using Import it in ... import { FormsModule,ReactiveForms } from '@angular/forms'; ... @NgModule({ imports: [ CommonModule,ReactiveForms ... }) export class PostsModule { } In post.component.ts import {FormCtrol} from '@angular/forms'; q:FormCtrol; constructor(){ this.q.valueChanges .debounceTime(500) .distinctUntilChanged() .flatMap(term => this.postService.getPosts({ q: term })) .subscribe((res: Array<Post>) => this.posts = res); }
The template can be more simple,eg. <form class="form-inline"> <div class="form-group" "> <input type="text" name="q" class="form-control" [formCtrol]="q"/> </div> <button type="submit" class="btn btn-outline-info">{{'search'}}</button> </form> Now try to input some texts in the serach box. And watch http hit logging in Browser console. Source codesGrab the sample codes from Github. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |