Angular4で登録機能を作る|AngularでWebサイト作成
Angularの学習の為に、AngularでWebサイトを作ってみることにしました(Angularのバージョンは4.3.6です)。
適宜作業内容をまとめていきます。
基本的な部分は公式チュートリアルなどを参考にしながら進めています。
今回は登録画面のコンポーネントを作成していきます。
開発環境
・OS:Windows8.1 64bit
・node:v7.2.1
・npm:4.0.5
・Angular:4.3.6
・開発ツール:VisualStudioCode
手順
手順1.登録テンプレートの作成
登録用のHTMLテンプレート(useradd.component.html)を作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | < h1 >ユーザ追加</ h1 > < div id = "contents" > < div > < table class = "table" > < tr > < th >名前: </ th > < td > < input class = "form-control" name = "name" [(ngModel)]="name" placeholder = "ユーザ名" > </ td > </ tr > < tr > < td colspan = "2" style = "text-align:center;" > < button class = "btn btn-primary" (click)="back()">戻る</ button > < button class = "btn btn-success" (click)="add()"> 追加 </ button > </ td > </ tr > </ table > </ div > </ div > |
手順2.addメソッドをcomponentに追加
useradd.component.tsを以下の様に作成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import { Component, OnInit } from '@angular/core' ; import { User} from './user' import { UserService } from './user.service' import { ActivatedRoute, Params } from '@angular/router' ; import { Location } from '@angular/common' ; import 'rxjs/add/operator/switchMap' ; @Component({ selector: 'app-user' , templateUrl: './useradd.component.html' , }) export class UserAddComponent implements OnInit { //@Input() user: User= new User name: string constructor( private userservice: UserService, private route: ActivatedRoute, private location: Location, ) { } ngOnInit() {} back(): void { this .location.back(); } add(): void { this .user.name = this .name.trim() if (! this .user.name) { return ;} this .userservice.create( this .user) .then((user: User) => { this .back(); }); } } |
手順3.確認(サーバ側で要設定)
登録の例も一覧・詳細表示や削除処理同様に、実際はサーバ側でAPIを用意しなければなりませんが、用意できたらブラウザからリクエストすれば登録処理が実行できるはずです。
(ただし、別サーバへリクエストを投げる場合はCORS(Cross Origin Resource Sharing)対応をしておく必要があります)。
感想
今回は登録用のコンポーネントを作成しました。次回は詳細画面のコンポーネントで編集処理が行えるようにコンポーネントを修正していきます。
WEBアプリケーション関連 人気連載リンク
基礎からPHPWEBアプリ解発を学ぶなら・・
PHP基礎 連載
より実践的なWEBアプリ開発講座!Bootstrap活用を学ぶなら・・
魁!小野の塾 連載