1646489880
Angular CRUDとは、データ機能の作成、読み取り、更新、削除で構成されるアプリケーションを意味します。これは、新しいAngularフレームワークを使用してCRUD(作成、読み取り、更新、削除)Webアプリケーションを構築するための包括的なガイドです。Angularがリリースされたばかりで、いくつかの新機能と改善が含まれています。
まず、Angular CLIを使用してAngularをインストールし、次にフロントエンドとバックエンドの開発を続けます。
古い@angular / cliバージョンを使用している場合は、次のコマンドを実行して最新バージョンをインストールできます。
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli
問題が発生した場合は、AngularCLIをバージョン7に更新する方法を確認してください。 Angular CLIを更新するのに役立ち、まったく新しいAngularsevenプロジェクトを作成します。
さて、次のコマンドを入力すると、 AngularCLIが更新されたことがわかります。
次に、次のコマンドを使用して新しいAngularプロジェクトを作成します。
ng new angular7crud
cd angular7crud
プロジェクトフォルダー内に入った後、次のコマンドを使用してVisual StudioCodeでプロジェクトを開きます。使用していない場合は、使用を開始してください。これは、 Javascript開発に最適なエディターです。
code .
インストール時に、アプリケーションのルーティングを有効にしました。 Angularボイラープレートの取り付け中にプロンプトが表示されるため、 Angularの新機能です。src >> appディレクトリ内のapp-routing.module.ts ファイルと呼ばれるファイルを確認できます。
次に、次のコマンドを使用してBootstrap 4 CSSFramework をインストールします。
npm install bootstrap --save
次に、 angular.json ファイル内に追加し ます。
"styles": [
"src/styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
これで、プロジェクトでBootstrap4クラスを使用できるようになりました。
次のコマンドを使用して、Angular開発サーバーを起動します。
ng serve -o
ユーザーがフォームからユーザー 名、会社名、 GST番号を入力して送信できるプロジェクトを作成します。値が正しくない場合、フロントエンドで検証され、フォームは送信されません。一方、すべての値が完全であると思われる場合は、フォームをバックエンドAPIに送信し、 MongoDBデータベース内に値を保存します。
それで、今、私たちは仕事をするためにいくつかの角度のあるコンポーネントを作成します。
次のコマンドを入力して、Angularコンポーネントを生成します。作成、読み取り、更新の操作を行います。したがって、3つのコンポーネントを作成します。
ng g c gst-add --spec=false
ng g c gst-get --spec=false
ng g c gst-edit --spec=false
3つのコンポーネントはすべて、app.module.ts ファイル内に自動的に登録されます。app-routing.module.ts ファイル内でAngularコンポーネントのルーティングを構成する必要があります。
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { GstAddComponent } from './gst-add/gst-add.component';
import { GstEditComponent } from './gst-edit/gst-edit.component';
import { GstGetComponent } from './gst-get/gst-get.component';
const routes: Routes = [
{
path: 'business/create',
component: GstAddComponent
},
{
path: 'business/edit/:id',
component: GstEditComponent
},
{
path: 'business',
component: GstGetComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
これで、 app.component.html ファイル内に<router-outlet> ディレクティブがあることがわかります。このディレクティブは、ルートURIに基づいてさまざまなコンポーネントをレンダリングするのに役立ちます。
app.component.html ファイル内に次のコードを 記述します。
<nav class="navbar navbar-expand-sm bg-light">
<div class="container-fluid">
<ul class="navbar-nav">
<li class="nav-item">
<a routerLink="business/create" class="nav-link" routerLinkActive="active">
Create Business
</a>
</li>
<li class="nav-item">
<a routerLink="business" class="nav-link" routerLinkActive="active">
Business
</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<router-outlet></router-outlet>
</div>
ファイルを保存してブラウザに移動し、2つのリンクをクリックします。ナビゲーションに基づいてさまざまなコンポーネントを確認できることがわかります。
次のコマンドを入力して、 ng2-slim-loading-barライブラリをインストールします。
npm install ng2-slim-loading-bar --save
そのため、今すぐサードパーティのパッケージをインストールすると、Angularと互換性がなくなります。Angular パッケージとサードパーティパッケージの間のギャップを埋める ために、次のライブラリをインストールする必要があります。それだ。
npm install rxjs-compat --save
次に、 app.module.ts ファイル内に SlimLoadingBarModule をインポートし ます。
// app.module.ts
import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';
imports: [
...
SlimLoadingBarModule
],
次のステップは、 src >> styles.css ファイル内にライブラリを使用したスタイル設定を含めることです。
@import "../node_modules/ng2-slim-loading-bar/style.css";
Angular RouterModuleは、次のイベントモジュールを提供します。
次に、 app.component.ts ファイル内に次のコードを記述し ます。
// app.component.ts
import { Component } from '@angular/core';
import {SlimLoadingBarService} from 'ng2-slim-loading-bar';
import { NavigationCancel,
Event,
NavigationEnd,
NavigationError,
NavigationStart,
Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular7crud';
constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
this._router.events.subscribe((event: Event) => {
this.navigationInterceptor(event);
});
}
private navigationInterceptor(event: Event): void {
if (event instanceof NavigationStart) {
this._loadingBar.start();
}
if (event instanceof NavigationEnd) {
this._loadingBar.complete();
}
if (event instanceof NavigationCancel) {
this._loadingBar.stop();
}
if (event instanceof NavigationError) {
this._loadingBar.stop();
}
}
}
ルーティングイベントをインターセプトし、すべてのルートにローディングバーコンポーネントを追加して、ルートを変更するたびにルーティング表示を確認できるようにします。
ルーティングインジケータを表示するための最後の変更は、ページ上部のapp.component.html ファイル内にng2-slim-loading-barディレクティブ を追加することです。
<ng2-slim-loading-bar color="blue"></ng2-slim-loading-bar>
<nav class="navbar navbar-expand-sm bg-light">
<div class="container-fluid">
<ul class="navbar-nav">
<li class="nav-item">
<a routerLink="business/create" class="nav-link" routerLinkActive="active">
Create Business
</a>
</li>
<li class="nav-item">
<a routerLink="business" class="nav-link" routerLinkActive="active">
Business
</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<router-outlet></router-outlet>
</div>
ファイルを保存してターミナルに移動し、エラーがあるかどうかを確認します。エラーがない場合は、ブラウザに移動してルートを変更します。これで、ルーティングインジケータが表示されることがわかります。
gst-add.component.html ファイル 内 に、次のブートストラップ4フォームを追加します。
<div class="card">
<div class="card-body">
<form>
<div class="form-group">
<label class="col-md-4">Person Name</label>
<input type="text" class="form-control" />
</div>
<div class="form-group">
<label class="col-md-4">Business Name </label>
<input type="text" class="form-control" />
</div>
<div class="form-group">
<label class="col-md-4">Business GST Number </label>
<input type="text" class="form-control" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Business</button>
</div>
</form>
</div>
</div>
ReactiveFormsModuleを使用します。したがって、 Angular Form Validationを初めて使用する場合は、このブログのこの記事Angular FormValidationを確認してください。
次に、 app.module.ts ファイル内に ReactiveFormsModule をインポートし ます。
// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
imports: [
...
ReactiveFormsModule
],
次に、 app.component.ts ファイルのコードを作成する必要があり ます。これはテンプレート駆動型のフォームではないことを忘れないでください。そのため、 app.component.ts ファイル内のコードを変更します。
まず、 FormGroup、FormBuilder、Validators モジュールを @ angle / formsからインポートします。
また、コンストラクターを作成し、 FormBuilderをインスタンス化します。
したがって、 gst-add.component.ts ファイル内に次のコードを記述し ます。
// gst-add.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-gst-add',
templateUrl: './gst-add.component.html',
styleUrls: ['./gst-add.component.css']
})
export class GstAddComponent implements OnInit {
angForm: FormGroup;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.angForm = this.fb.group({
person_name: ['', Validators.required ],
business_name: ['', Validators.required ],
business_gst_number: ['', Validators.required ]
});
}
ngOnInit() {
}
}
フォームビルダーを使用してすべての検証を処理しました。そのため、そのコンストラクターでは、検証ルールを使用してフォームを作成しています。この例では、3つのフィールドがあります。入力テキストが空の場合、エラーが発生するため、表示する必要があります。
ここで、 gst-add.component.html ファイル内に次のコードを記述し ます。
<div class="card">
<div class="card-body">
<form [formGroup]="angForm" novalidate>
<div class="form-group">
<label class="col-md-4">Person Name</label>
<input type="text" class="form-control" formControlName="person_name" #person_name />
</div>
<div *ngIf="angForm.controls['person_name'].invalid && (angForm.controls['person_name'].dirty || angForm.controls['person_name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['person_name'].errors.required">
Person Name is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Business Name </label>
<input type="text" class="form-control" formControlName="business_name" #business_name />
</div>
<div *ngIf="angForm.controls['business_name'].invalid && (angForm.controls['business_name'].dirty || angForm.controls['business_name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['business_name'].errors.required">
Person Business is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Business GST Number </label>
<input type="text" class="form-control" formControlName="business_gst_number" #business_gst_number />
</div>
<div *ngIf="angForm.controls['business_gst_number'].invalid && (angForm.controls['business_gst_number'].dirty || angForm.controls['business_gst_number'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['business_gst_number'].errors.required">
Business GST Number is required.
</div>
</div>
<div class="form-group">
<button type="submit"
[disabled]="angForm.pristine || angForm.invalid"
class="btn btn-primary">Add Business</button>
</div>
</form>
</div>
</div>
ファイルを保存してブラウザに移動すると、入力ボックスに値を入力しないかどうかを確認でき、エラーが表示されます。
app.module.ts ファイル内に HttpClientModule をインポートし ます。
// app.module.ts
import { HttpClientModule } from '@angular/common/http';
imports: [
...
HttpClientModule
],
src >> app フォルダー内 に、 Business.ts というファイルを1つ作成 し、次のコードを追加します。
// Business.ts
export default class Business {
person_name: String;
business_name: String;
business_gst_number: Number;
}
次のコマンドを入力して、サービスファイルを生成します。
ng g service business --spec=false
したがって、プライマリ business.service.ts ファイルは次のようになります。
// business.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class BusinessService {
constructor() { }
}
次に、 business.service.ts ファイルを app.module.ts ファイルにインポートし ます。
// app.module.ts
import { BusinessService } from './business.service';
providers: [ BusinessService ],
データを含むHTTPPOSTリクエストをNode.jsサーバーに送信し、データをMongoDBデータベースに保存するコードを作成する必要があります。
business.service.ts ファイル内に次のコードを記述し ます。
// business.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BusinessService {
uri = 'http://localhost:4000/business';
constructor(private http: HttpClient) { }
addBusiness(person_name, business_name, business_gst_number) {
const obj = {
person_name: person_name,
business_name: business_name,
business_gst_number: business_gst_number
};
console.log(obj);
this.http.post(`${this.uri}/add`, obj)
.subscribe(res => console.log('Done'));
}
}
バックエンドAPIURLを定義しましたが、まだバックエンドを作成していませんが、いくつかの手順で作成します。
クリックイベントを[ビジネスの追加]ボタンに追加する必要があります。したがって、 gst-add.component.html ファイル内に次のコードを追加します。
<div class="form-group">
<button (click)="addBusiness(person_name.value, business_name.value, business_gst_number.value)"
[disabled]="angForm.pristine || angForm.invalid"
class="btn btn-primary">
Add Business
</button>
</div>
したがって、エラーがない場合は、フォームを送信すると、コンポーネントの addBusiness 関数が呼び出されます。そこから、Angularサービスを呼び出し、サービスはHTTPPostリクエストをNode.jsサーバーに送信します。
次に、 gst-add.component.ts ファイル内にaddBusiness 関数を 追加し ます。したがって、gst-add.component.ts ファイル内に次のコードを記述し ます。
// gst-add.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { BusinessService } from '../business.service';
@Component({
selector: 'app-gst-add',
templateUrl: './gst-add.component.html',
styleUrls: ['./gst-add.component.css']
})
export class GstAddComponent implements OnInit {
angForm: FormGroup;
constructor(private fb: FormBuilder, private bs: BusinessService) {
this.createForm();
}
createForm() {
this.angForm = this.fb.group({
person_name: ['', Validators.required ],
business_name: ['', Validators.required ],
business_gst_number: ['', Validators.required ]
});
}
addBusiness(person_name, busines_name, business_gst_number) {
this.bs.addBusiness(person_name, busines_name, business_gst_number);
}
ngOnInit() {
}
}
ここでは、関数を定義し、 business.service.ts ファイルもインポートしました。次に、コンストラクター内でオブジェクトをインスタンス化し、businsess.service.tsファイルの関数を呼び出します。
addBusiness 関数は business.service.ts ファイル内にすでにコーディングされてい ます。次に、バックエンドAPIを構成する必要があります。
角度ルートフォルダー内に、apiというフォルダーを1つ作成し、そのフォルダー内に移動します。Angularとは完全に別のプロジェクトになることを忘れないでください。そのため、そのnode_modulesはAngularとは異なります。
api フォルダー内のターミナルを開き、 次のコマンドを入力します。
npm init -y
次のノード固有のモジュールをインストールします。
npm install --save express body-parser cors mongoose
毎回ノードサーバーを再起動するわけではありません。ファイルを変更します。だから私はnodemonサーバーをインストールしています。 server.js ファイルを変更すると、 node.jsサーバー が自動的に再起動し ます。
npm install nodemon --save-dev
次に、 api フォルダー内に、 server.js ファイルと呼ばれる1つのファイルを作成します。
// server.js
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose');
const app = express();
let port = process.env.PORT || 4000;
const server = app.listen(function(){
console.log('Listening on port ' + port);
});
次に、MongoDBデータベースをnode.jsアプリケーションに接続します。
MongoDBデータベースをインストールしていない場合は、インストールしてmongodbサーバーを起動します。
次のコマンドを入力して、 MongoDB サーバーを起動します。
mongod
これで、データベースに接続しました。
api ルートプロジェクトフォルダー 内に DB.jsというファイルを1つ作成 します。次に、DB.js ファイル内に次のコードを記述します。
// DB.js
module.exports = {
DB: 'mongodb://localhost:27017/ng7crud'
};
この DB.jsファイルをserver.js ファイル内に インポートし、mongooseライブラリを使用 してMongoDBとのデータベース接続 を セットアップし ます。Mongooseを使用して、MongooseORMを使用してデータベースにデータを保存することもできます。
server.js ファイル 内に次のコードを記述して、 MongoDB アプリケーションを Node.js サーバーに接続します。
// server.js
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./DB');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
const app = express();
app.use(bodyParser.json());
app.use(cors());
const port = process.env.PORT || 4000;
const server = app.listen(port, function(){
console.log('Listening on port ' + port);
});
ファイルを保存してターミナルに移動し、ノードサーバーを起動します。
nodemon server
したがって、現在、3台のサーバーが実行されています。
3つのサーバーすべてがエラーなしで正常に実行されていることを忘れないでください。そうしないと、アプリケーションが機能しません。
ルートとモデルと呼ばれるAPI ルート フォルダー内に2つのフォルダーを作成する必要があります。
モデルの フォルダーに、 Business.jsというモデルを1つ作成します。
// Business.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Define collection and schema for Business
let Business = new Schema({
person_name: {
type: String
},
business_name: {
type: String
},
business_gst_number: {
type: Number
}
},{
collection: 'business'
});
module.exports = mongoose.model('Business', Business);
そこで、ビジネスコレクションのスキーマを定義しました。person_name、business_name、business_gst_numberという3つのフィールドがあります 。
ルート フォルダーに、business.route.jsというファイルを1つ作成します 。
business.route.js ファイル内にCRUDコードを記述し ます。
// business.route.js
const express = require('express');
const app = express();
const businessRoutes = express.Router();
// Require Business model in our routes module
let Business = require('../models/Business');
// Defined store route
businessRoutes.route('/add').post(function (req, res) {
let business = new Business(req.body);
business.save()
.then(business => {
res.status(200).json({'business': 'business in added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
// Defined get data(index or listing) route
businessRoutes.route('/').get(function (req, res) {
Business.find(function (err, businesses){
if(err){
console.log(err);
}
else {
res.json(businesses);
}
});
});
// Defined edit route
businessRoutes.route('/edit/:id').get(function (req, res) {
let id = req.params.id;
Business.findById(id, function (err, business){
res.json(business);
});
});
// Defined update route
businessRoutes.route('/update/:id').post(function (req, res) {
Business.findById(req.params.id, function(err, next, business) {
if (!business)
return next(new Error('Could not load Document'));
else {
business.person_name = req.body.person_name;
business.business_name = req.body.business_name;
business.business_gst_number = req.body.business_gst_number;
business.save().then(business => {
res.json('Update complete');
})
.catch(err => {
res.status(400).send("unable to update the database");
});
}
});
});
// Defined delete | remove | destroy route
businessRoutes.route('/delete/:id').get(function (req, res) {
Business.findByIdAndRemove({_id: req.params.id}, function(err, business){
if(err) res.json(err);
else res.json('Successfully removed');
});
});
module.exports = businessRoutes;
マングースモデルを使用して、データベースを保存、更新、および削除しました。Mongooseは、 MongoDBデータベースで使用されるORMです。ルートファイルにすべてのCRUD操作を設定しました。それらをserver.js ファイル内にインポートする必要があります。
したがって、最終的な server.js ファイルは次のようになります。
// server.js
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./DB');
const businessRoute = require('./routes/business.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/business', businessRoute);
const port = process.env.PORT || 4000;
const server = app.listen(port, function(){
console.log('Listening on port ' + port);
});
すべてのサーバーが稼働している場合は、ブラウザーに移動し、フォームデータに入力して、ビジネスを追加できます。成功すると、画面にこのようなものが表示されます。
これで、次のコマンドを使用してデータベースを確認できます。
まず、他の3つのタブがすべて現在使用されているため、4番目のタブでmongoシェルを開きます。
mongo
ここでは、値がMongoDBデータベースに保存されていることがわかります。はい!成功しました。
現在、残りの操作は読み取り、更新、および削除です。
gst-get.component.html ファイルに、次のコードを記述します。
<table class="table table-hover">
<thead>
<tr>
<td>Person Name</td>
<td>Business Name</td>
<td>GST Number</td>
<td colspan="2">Actions</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let business of businesses">
<td>{{ business.person_name }}</td>
<td>{{ business.business_name }}</td>
<td>{{ business.business_gst_number }}</td>
<td><a [routerLink]="['/edit', business._id]" class="btn btn-primary">Edit</a></td>
<td><a [routerLink]="" class="btn btn-danger">Delete</a></td>
</tr>
</tbody>
</table>
ここで、 business.service.ts ファイル内に、 MongoDBデータベースからビジネスデータをフェッチ してAngularアプリケーションに表示する関数を作成する必要があります。
// business.service.ts
getBusinesses() {
return this
.http
.get(`${this.uri}`);
}
このbusiness.service.ts ファイルとBusiness.ts ファイルをgst-get.component.ts ファイル内 に含める必要があります。
gst-get.component.ts ファイル内に次のコードを 記述します。
// gst-get.component.ts
import { Component, OnInit } from '@angular/core';
import Business from '../Business';
import { BusinessService } from '../business.service';
@Component({
selector: 'app-gst-get',
templateUrl: './gst-get.component.html',
styleUrls: ['./gst-get.component.css']
})
export class GstGetComponent implements OnInit {
businesses: Business[];
constructor(private bs: BusinessService) { }
ngOnInit() {
this.bs
.getBusinesses()
.subscribe((data: Business[]) => {
this.businesses = data;
});
}
}
ファイルを保存し、ブラウザに移動して、次のURLに切り替えます: http:// localhost:4200 / business。 あなたはビジネスのリストを見ることができます。
まず、_idを使用してMongoDBデータベースからデータをフェッチし、そのデータをgst-edit.component.html ファイルに表示する必要があります。
したがって、最初に、 gst-edit.component.ts ファイル内に次のコードを記述します。
// gst-edit.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { BusinessService } from '../business.service';
@Component({
selector: 'app-gst-edit',
templateUrl: './gst-edit.component.html',
styleUrls: ['./gst-edit.component.css']
})
export class GstEditComponent implements OnInit {
business: any = {};
angForm: FormGroup;
constructor(private route: ActivatedRoute,
private router: Router,
private bs: BusinessService,
private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.angForm = this.fb.group({
person_name: ['', Validators.required ],
business_name: ['', Validators.required ],
business_gst_number: ['', Validators.required ]
});
}
ngOnInit() {
this.route.params.subscribe(params => {
this.bs.editBusiness(params['id']).subscribe(res => {
this.business = res;
});
});
}
}
ここで、 gst-edit component.ts がレンダリングされると、 ngOnInit メソッドが呼び出され、ノードサーバーにHTTPリクエストが送信され、_idからデータがフェッチされてgst-edit.component.html ファイル内に表示され ます。
ここで、 business.service.ts ファイル 内で、HTTPリクエストを送信するためにeditBusiness 関数をコーディングする必要があります。
// business.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BusinessService {
uri = 'http://localhost:4000/business';
constructor(private http: HttpClient) { }
addBusiness(person_name, business_name, business_gst_number) {
const obj = {
person_name: person_name,
business_name: business_name,
business_gst_number: business_gst_number
};
this.http.post(`${this.uri}/add`, obj)
.subscribe(res => console.log('Done'));
}
getBusinesses() {
return this
.http
.get(`${this.uri}`);
}
editBusiness(id) {
return this
.http
.get(`${this.uri}/edit/${id}`);
}
}
最後に、gst-edit.component.html ファイル内にフォームを作成する必要があります。
<div class="card">
<div class="card-body">
<form [formGroup]="angForm" novalidate>
<div class="form-group">
<label class="col-md-4">Person Name</label>
<input type="text" class="form-control" formControlName="person_name" #person_name [(ngModel)] = "business.person_name" />
</div>
<div *ngIf="angForm.controls['person_name'].invalid && (angForm.controls['person_name'].dirty || angForm.controls['person_name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['person_name'].errors.required">
Person Name is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Business Name </label>
<input type="text" class="form-control" formControlName="business_name" #business_name [(ngModel)] = "business.business_name" />
</div>
<div *ngIf="angForm.controls['business_name'].invalid && (angForm.controls['business_name'].dirty || angForm.controls['business_name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['business_name'].errors.required">
Person Business is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Business GST Number </label>
<input type="text" class="form-control" formControlName="business_gst_number" #business_gst_number [(ngModel)] = "business.business_gst_number" />
</div>
<div *ngIf="angForm.controls['business_gst_number'].invalid && (angForm.controls['business_gst_number'].dirty || angForm.controls['business_gst_number'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['business_gst_number'].errors.required">
Business GST Number is required.
</div>
</div>
<div class="form-group">
<button (click)="updateBusiness(person_name.value, business_name.value, business_gst_number.value)"
[disabled]="angForm.invalid"
class="btn btn-primary">Update Business</button>
</div>
</form>
</div>
</div>
ファイルを保存し、リストページに移動し、編集ボタンをクリックして、データベースから入力されたフォームを確認します。
次のような警告も表示されます。このデモチュートリアルは無視してください。
forms.js:
1193formControlNameと同じフォームフィールドでngModelを使用しているようです。
リアクティブフォームディレクティブでのngModel入力プロパティとngModelChangeイベントの使用のサポートは
、Angular v6で非推奨になり、Angularv7で削除され
ました。
次に、データを更新します。 business.service.ts ファイル内に、データを更新する関数を記述する必要があります。
// business.service.ts
updateBusiness(person_name, business_name, business_gst_number, id) {
const obj = {
person_name: person_name,
business_name: business_name,
business_gst_number: business_gst_number
};
this
.http
.post(`${this.uri}/update/${id}`, obj)
.subscribe(res => console.log('Done'));
}
では、 gst-edit.component.ts ファイル内にupdateBusiness() 関数を記述します。
// gst-edit.component.ts
updateBusiness(person_name, business_name, business_gst_number) {
this.route.params.subscribe(params => {
this.bs.updateBusiness(person_name, business_name, business_gst_number, params['id']);
this.router.navigate(['business']);
});
ファイルを保存すると、データを更新できるようになります。
したがって、コンソールでエラーが見つからない場合は、データを正常に更新できます。
API呼び出しを行うための編集 および 更新サービス をすでに作成しました。したがって、これまで、このAngular CRUDの例は、作成、読み取り、更新 が完了してい ます。次に、 Deleteを見てください 。
gst-get.component.html ファイル内の削除ボタンでクリックイベントを定義する必要があります。
<tr *ngFor="let business of businesses">
<td>{{ business.person_name }}</td>
<td>{{ business.business_name }}</td>
<td>{{ business.business_gst_number }}</td>
<td><a [routerLink]="['edit', business._id]" class="btn btn-primary">Edit</a></td>
<td><a (click) = "deleteBusiness(business._id)" class="btn btn-danger">Delete</a></td>
</tr>
ここで、 deleteBusiness関数 をgst-get.component.ts ファイル内に 記述します。
// gst-get.component.ts
deleteBusiness(id) {
this.bs.deleteBusiness(id).subscribe(res => {
console.log('Deleted');
});
}
最後に、 business.service.ts ファイル内にdeleteBusiness() 関数を作成します。
// business.service.ts
deleteBusiness(id) {
return this
.http
.get(`${this.uri}/delete/${id}`);
}
最後に、削除機能を完了しました。
したがって、このチュートリアルでは、AngularのCRUD機能を完了しました。
1598940617
Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.
In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!
For Installing Angular on your Machine, there are 2 prerequisites:
First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js
Download and Install Node.js version suitable for your machine’s operating system.
Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:
· After executing the command, Angular CLI will get installed within some time. You can check it using the following command
Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:
To create a workspace:
#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli
1622597127
In this tutorial, we will learn how to build a full stack Spring Boot + Angular 12 example with a CRUD App. The back-end server uses Spring Boot with Spring Web MVC for REST Controller and Spring Data JPA for interacting with embedded database (H2 database). Front-end side is made with Angular 12, HttpClient, Router and Bootstrap 4.
Run both Project on same server/port:
How to Integrate Angular with Spring Boot Rest API
Contents [hide]
#angular #full stack #spring #angular #angular 12 #crud #h2 database #mysql #postgresql #rest api #spring boot #spring data jpa
1622600862
In this tutorial, we will learn how to build a full stack Angular 12 + Spring Boot + PostgreSQL example with a CRUD App. The back-end server uses Spring Boot with Spring Web MVC for REST Controller and Spring Data JPA for interacting with PostgreSQL database. Front-end side is made with Angular 12, HTTPClient, Router and Bootstrap 4.
Older versions:
– Angular 10 + Spring Boot + PostgreSQL example: CRUD App
– Angular 11 + Spring Boot + PostgreSQL example: CRUD App
Contents [hide]
#angular #full stack #spring #angular #angular 12 #crud #postgresql #rest api #spring boot #spring data jpa
1593184320
What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.
Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.
We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.
Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule
],
bootstrap: [AppComponent]
})
Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:
#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular
1589624684
I am going to share with you how to create CRUD Operations using Angular 10/9/8 and Firebase real-time NoSQL cloud database. We’ll be using Angular’s Reactive Forms service for managing the user submitted data in our web application.
For the demo purpose, we’ll be creating a basic student record management system in which a school admin can perform following tasks:
#angular #bootstrap #firebase #popular tutorials #typescript #angular crud operations #angular firebase #firebase crud operations #javascript