Duck Hwan

1679135460

Bootstrap 4로 Angular CRUD를 만드는 방법

이 튜토리얼에서는 Bootstrap 4 스타일로 Angular 11 CRUD 애플리케이션을 빌드하여 REST 웹 API를 사용하고 데이터를 생성, 읽기, 수정 및 검색하는 방법을 배웁니다. Bootstrap 4를 사용하여 Angular 11 CRUD 애플리케이션을 빌드하려면 다음 단계를 따릅니다.

  • 1단계: 새 Angular 11 프로젝트 만들기
  • 2단계: Angular 11 CRUD 구성 요소 및 서비스 생성
  • 3단계: 가져오기 FormsModuleHttpClientModule
  • 4단계: CRUD 구성 요소에 대한 경로 추가
  • 5단계: 부트스트랩 4를 사용하여 탐색 모음 추가 및 스타일 지정
  • 6단계: Angular 11 CRUD 서비스 생성
  • 7단계: Angular 11 CRUD 구성 요소 구현
  • 8단계: Angular 11 CRUD 앱 제공

1단계: 새 Angular 11 프로젝트 만들기

CLI를 사용하여 새 Angular 11 프로젝트를 생성하여 시작하겠습니다. 다음 명령을 실행해야 합니다.

$ ng new Angular11CRUDExample 

CLI는 몇 가지 질문을 합니다. Angular 라우팅을 추가하시겠습니까? 예에 대해 y를 입력 하고 어떤 스타일시트 형식을 사용하시겠습니까? CSS를 선택합니다 .

2단계: Angular 11 CRUD 구성 요소 및 서비스 생성

다음으로 Angular CLI를 사용하여 다음과 같이 여러 구성 요소와 서비스를 생성해야 합니다.

$ ng generate service services/product
$ ng g c components/product-create
$ ng g c components/product-details
$ ng g c components/product-list

서버에 HTTP 요청을 보내는 데 필요한 메서드를 제공하는 세 가지 구성 요소 및 제품 서비스를 product-list생성 product-details했습니다 .product-create

다음 아티팩트도 있습니다.

src/app/app-routing.module.ts모듈에는 각 구성 요소에 대한 경로가 포함됩니다. 이 파일은 라우팅에 대해 예라고 답한 경우 Angular CLI에서 자동으로 생성됩니다. – 이 App구성 요소에는 라우터 보기 및 탐색 모음이 포함되어 있습니다.
src/app/app.module.ts모듈은 Angular 구성 요소를 선언하고 Angular와 같은 필요한 모듈을 가져옵니다 HttpClient.

3단계: 가져오기 FormsModule및HttpClientModule

우리는 Angular의 자체 모듈에서 제공되는 CRUD 애플리케이션에서 http 클라이언트 및 양식을 사용할 것이므로 이러한 모듈을 가져와야 FormsModule합니다 HttpClientModule.

다음과 같이 파일을 열고 src/app/app.module.ts가져옵니다 FormsModule.HttpClientModule

// [...]
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [ ... ],
  imports: [
    ...
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4단계: CRUD 구성 요소에 대한 경로 추가

애플리케이션 UI를 구성하는 구성 요소가 있지만 Angular 11 라우터를 사용하여 구성 요소 간에 탐색할 수 있도록 구성 요소를 경로와 연결해야 합니다.

세 가지 경로를 생성합니다.

– 구성 요소 /products의 경우 product-list/products/:id구성 product-details요소의 경우 – 구성 요소 /create의 경우product-create

파일을 열고 src/app/app-routing.module.ts다음과 같이 업데이트합니다.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { ProductListComponent } from './components/product-list/product-list.component';
import { ProductDetailsComponent } from './components/product-details/product-details.component';
import { ProductCreateComponent } from './components/product-create/product-create.component';

const routes: Routes = [
  { path: '', redirectTo: 'products', pathMatch: 'full' },
  { path: 'products', component: ProductListComponent },
  { path: 'products/:id', component: ProductDetailsComponent },
  { path: 'create', component: ProductCreateComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

5단계: 부트스트랩 4를 사용하여 탐색 모음 추가 및 스타일 지정

다음으로 부트스트랩 4를 응용 프로그램과 탐색 모음에 추가해 보겠습니다.

UI 스타일을 지정하기 위해 부트스트랩 4를 사용할 것이므로 프로젝트에 설치해야 합니다. Angular 프로젝트에 부트스트랩을 추가하는 방법에 대한 세 가지 방법을 확인하십시오 .

파일을 열고 src/app/app.component.html다음과 같이 업데이트합니다.

<div>
  <nav class="navbar navbar-expand navbar-dark bg-dark">
    <a href="#" class="navbar-brand">Techiediaries</a>
    <div class="navbar-nav mr-auto">
      <li class="nav-item">
        <a routerLink="products" class="nav-link">Products</a>
      </li>
      <li class="nav-item">
        <a routerLink="create" class="nav-link">Create</a>
      </li>
    </div>
  </nav>

  <div class="container mt-5">
    <router-outlet></router-outlet>
  </div>
</div>

부트스트랩 탐색 모음을 만들고 라우터 콘센트를 컨테이너 div로 래핑했습니다.

6단계: Angular 11 CRUD 서비스 생성

HTTPClient다음으로 Angular 11을 사용하여 REST API 서버에 HTTP 요청을 보내는 CRUD 서비스를 만들어야 합니다 .

파일을 열고 src/services/product.service.ts다음과 같이 업데이트합니다.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

const baseURL = 'http://localhost:8080/api/products';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private httpClient: HttpClient) { }

  readAll(): Observable<any> {
    return this.httpClient.get(baseURL);
  }

  read(id): Observable<any> {
    return this.httpClient.get(`${baseURL}/${id}`);
  }

  create(data): Observable<any> {
    return this.httpClient.post(baseURL, data);
  }

  update(id, data): Observable<any> {
    return this.httpClient.put(`${baseURL}/${id}`, data);
  }

  delete(id): Observable<any> {
    return this.httpClient.delete(`${baseURL}/${id}`);
  }

  deleteAll(): Observable<any> {
    return this.httpClient.delete(baseURL);
  }

  searchByName(name): Observable<any> {
    return this.httpClient.get(`${baseURL}?name=${name}`);
  }
}

7단계: Angular 11 CRUD 구성 요소 구현

이전에 세 가지 구성 요소를 생성하여 라우터에 추가했으므로 이제 각 구성 요소의 실제 기능을 구현해 보겠습니다.

새 제품 구성 요소 생성

name이 구성 요소는 두 개의 필드 및 와 함께 새 제품을 제출하기 위한 양식을 제공합니다 description. 메서드 를 주입하고 호출합니다 ProductService.create().

파일을 열고 src/components/product-create/product-create.component.ts다음과 같이 업데이트합니다.

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';

@Component({
  selector: 'app-product-create',
  templateUrl: './product-create.component.html',
  styleUrls: ['./product-create.component.css']
})
export class ProductCreateComponent implements OnInit {
  product = {
    name: '',
    description: '',
    available: false
  };
  submitted = false;

  constructor(private productService: ProductService) { }

  ngOnInit(): void {
  }

  createProduct(): void {
    const data = {
      name: this.product.name,
      description: this.product.description
    };

    this.productService.create(data)
      .subscribe(
        response => {
          console.log(response);
          this.submitted = true;
        },
        error => {
          console.log(error);
        });
  }

  newProduct(): void {
    this.submitted = false;
    this.product = {
      name: '',
      description: '',
      available: false
    };
  }

}

그런 다음 src/components/product-create/product-create.component.html파일을 열고 다음과 같이 업데이트합니다.

<div style="width: 500px; margin: auto;">
  <div class="submit-form">
    <div *ngIf="!submitted">
      <div class="form-group">
        <label for="name">Name</label>
        <input
          type="text"
          class="form-control"
          id="name"
          required
          [(ngModel)]="product.name"
          name="name"
        />
      </div>

      <div class="form-group">
        <label for="description">Description</label>
        <input
          class="form-control"
          id="description"
          required
          [(ngModel)]="product.description"
          name="description"
        />
      </div>

      <button (click)="createProduct()" class="btn btn-success">Create</button>
    </div>

    <div *ngIf="submitted">
      <h3>You successfully created a product!</h3>
      <button class="btn btn-success" (click)="newProduct()">New..</button>
    </div>
  </div>
</div>

제품 구성 요소 목록 표시

다음으로 다음 서비스 메서드를 사용하는 제품 목록 구성 요소를 구현해 보겠습니다.

  • readAll()
  • deleteAll()
  • searchByName()

파일을 열고 src/components/product-list/product-list.component.ts다음과 같이 업데이트합니다.

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {

  products: any;
  currentProduct = null;
  currentIndex = -1;
  name = '';

  constructor(private productService: ProductService) { }

  ngOnInit(): void {
    this.readProducts();
  }

  readProducts(): void {
    this.productService.readAll()
      .subscribe(
        products => {
          this.products = products;
          console.log(products);
        },
        error => {
          console.log(error);
        });
  }

  refresh(): void {
    this.readProducts();
    this.currentProduct = null;
    this.currentIndex = -1;
  }

  setCurrentProduct(product, index): void {
    this.currentProduct = product;
    this.currentIndex = index;
  }

  deleteAllProducts(): void {
    this.productService.deleteAll()
      .subscribe(
        response => {
          console.log(response);
          this.readProducts();
        },
        error => {
          console.log(error);
        });
  }

  searchByName(): void {
    this.productService.searchByName(this.name)
      .subscribe(
        products => {
          this.products = products;
          console.log(products);
        },
        error => {
          console.log(error);
        });
  }
}

파일을 열고 src/components/product-list/product-list.component.html다음과 같이 업데이트합니다.

<div class="list row">
  <div class="col-md-8">
    <div class="input-group mb-4">
      <input
        type="text"
        class="form-control"
        placeholder="Search by name"
        [(ngModel)]="name"
      />
      <div class="input-group-append">
        <button
          class="btn btn-outline-secondary"
          type="button"
          (click)="searchByName()"
        >
          Search
        </button>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <h4>Product List</h4>
    <ul class="list-group">
      <li
        class="list-group-item"
        *ngFor="let product of products; let i = index"
        [class.active]="i == currentIndex"
        (click)="setCurrentProduct(product, i)"
      >

      </li>
    </ul>

    <button class="m-4 btn btn-sm btn-danger" (click)="deleteAllProducts()">
      Delete All
    </button>
  </div>
  <div class="col-md-6">
    <div *ngIf="currentProduct">
      <h4>Product</h4>
      <div>
        <label><strong>Name:</strong></label> 
      </div>
      <div>
        <label><strong>Description:</strong></label>

      </div>
      <div>
        <label><strong>Status:</strong></label>

      </div>

      <a class="badge badge-warning" routerLink="/products/">
        Edit
      </a>
    </div>

    <div *ngIf="!currentProduct">
      <br />
      <p>Please click on a product</p>
    </div>
  </div>
</div>

상품의 수정 버튼을 클릭하면 URL 이 포함된 상품 상세 페이지로 이동합니다 /products/:id.

제품 세부 정보 구성 요소

다음으로 Angular 11 CRUD 애플리케이션의 제품 세부 정보 구성 요소를 구현해 보겠습니다.

파일을 열고 src/components/product-details/product-details.component.ts다음과 같이 업데이트합니다.

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {
  currentproduct = null;
  message = '';

  constructor(
    private productService: ProductService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit(): void {
    this.message = '';
    this.getProduct(this.route.snapshot.paramMap.get('id'));
  }

  getProduct(id): void {
    this.productService.read(id)
      .subscribe(
        product => {
          this.currentProduct = product;
          console.log(product);
        },
        error => {
          console.log(error);
        });
  }

  setAvailableStatus(status): void {
    const data = {
      name: this.currentProduct.name,
      description: this.currentProduct.description,
      available: status
    };

    this.productService.update(this.currentProduct.id, data)
      .subscribe(
        response => {
          this.currentProduct.available = status;
          console.log(response);
        },
        error => {
          console.log(error);
        });
  }

  updateProduct(): void {
    this.productService.update(this.currentProduct.id, this.currentProduct)
      .subscribe(
        response => {
          console.log(response);
          this.message = 'The product was updated!';
        },
        error => {
          console.log(error);
        });
  }

  deleteProduct(): void {
    this.productService.delete(this.currentProduct.id)
      .subscribe(
        response => {
          console.log(response);
          this.router.navigate(['/products']);
        },
        error => {
          console.log(error);
        });
  }
}

파일을 열고 src/components/product-details/product-details.component.html다음과 같이 업데이트합니다.

<div style="width: 500px; margin: auto;">
  <div *ngIf="currentProduct" class="edit-form">
    <h4>Product</h4>
    <form>
      <div class="form-group">
        <label for="title">Name</label>
        <input
          type="text"
          class="form-control"
          id="name"
          [(ngModel)]="currentProduct.name"
          name="name"
        />
      </div>
      <div class="form-group">
        <label for="description">Description</label>
        <input
          type="text"
          class="form-control"
          id="description"
          [(ngModel)]="currentProduct.description"
          name="description"
        />
      </div>

      <div class="form-group">
        <label><strong>Status:</strong></label>

      </div>
    </form>

    <button
      class="badge badge-primary mr-2"
      *ngIf="currentProduct.available"
      (click)="setAvailableStatus(false)"
    >
      Set Not Available
    </button>
    <button
      *ngIf="!currentProduct.available"
      class="badge badge-primary mr-2"
      (click)="setAvailableStatus(true)"
    >
      Set Available
    </button>

    <button class="badge badge-danger mr-2" (click)="deleteProduct()">
      Delete
    </button>

    <button
      type="submit"
      class="badge badge-success"
      (click)="updateProduct()"
    >
      Update
    </button>
    <p></p>
  </div>

  <div *ngIf="!currentProduct">
    <br />
    <p>This product is not accessible</p>
  </div>
</div>

8단계: Angular 11 CRUD 앱 제공

명령줄 인터페이스로 돌아가서 프로젝트 디렉터리의 루트로 이동했는지 확인하고 다음 명령을 실행하여 로컬 컴퓨터에서 라이브 개발 서버를 시작합니다.

$ cd Angular11CRUDExample
$ ng serve    

웹 브라우저로 이동하고 http://localhost:4200/주소로 이동하여 앱 테스트를 시작합니다.

이 자습서에서는 Web REST API용 Angular 11 CRUD 애플리케이션을 구축했으며 UI 스타일을 지정하기 위해 Bootstrap 4를 사용했습니다.

 

What is GEEK

Buddha Community

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

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.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

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!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

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.

Npm Package Manager

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:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

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.

What is a Component in Angular?

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']
})

Role of App Module

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]
})

What is Data Binding?

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:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

Ayyaz Zafar

1624138795

Angular Material Autocomplete - Multiple Use Cases covered

Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.

Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects

Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w

#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial

Angular Janker

Angular Janker

1604022104

How to Create Angular CRUD with Bootstrap 4

In this tutorial, we’ll be learning how to build an Angular 11 CRUD application with Bootstrap 4 styles to consume a REST Web API, create, read, modify, and search data. To build an Angular 11 CRUD application with Bootstrap 4 we follow these steps.

  • Step 1 : Creating a New Angular 11 Project
  • Step 2 :  Generating Angular 11 CRUD Components and Service
  • Step 3 : Importing FormsModule and HttpClientModule
  • Step 4 : Adding Routes for the CRUD Components
  • Step 5 : Adding and Styling a Navigation Bar Using Bootstrap 4
  • Step 6 : Creating an Angular 11 CRUD Service
  • Step 7 : Implementing the Angular 11 CRUD Components
  • Step 8 : Serving the Angular 11 CRUD App

Step 1 : Creating a New Angular 11 Project

Let's get started by generating a new Angular 11 project using the CLI. You need to run the following command:

$ ng new Angular11CRUDExample 

The CLI will ask you a couple of questions — If Would you like to add Angular routing? Type y for Yes and Which stylesheet format would you like to use? Choose CSS.

Step 2 :  Generating Angular 11 CRUD Components and Service

Next, we need to generate a bunch of components and a service using the Angular CLI as follows:

$ ng generate service services/product
$ ng g c components/product-create
$ ng g c components/product-details
$ ng g c components/product-list

We have generated three components product-list, product-details, product-create and a product service that provides the necessary methods for sending HTTP requests to the server.

We also have the following artifacts:

– The src/app/app-routing.module.ts module will contain routes for each component. This file is automatically generated by Angular CLI when you answered Yes for routing. – The App component contains the router view and navigation bar.
– The src/app/app.module.ts module declares our Angular components and import the necessary modules such Angular HttpClient.

Step 3 : Importing FormsModule and HttpClientModule

We'll be using the http client and forms in our CRUD application which are provided in its own modules in Angular so we'll need to import these modules — FormsModule and HttpClientModule.

Open src/app/app.module.ts file and import FormsModule, HttpClientModule as follows:

// [...]
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [ ... ],
  imports: [
    ...
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4 : Adding Routes for the CRUD Components

We have the components that compose our application UI but we need to link them with their routes to be able to navigate between them using the Angular 11 Router.

We'll create three routes:

/products for the product-list component, – /products/:id for the product-details component, – /create for theproduct-create component.

Open the src/app/app-routing.module.ts file and update it as follows:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { ProductListComponent } from './components/product-list/product-list.component';
import { ProductDetailsComponent } from './components/product-details/product-details.component';
import { ProductCreateComponent } from './components/product-create/product-create.component';

const routes: Routes = [
  { path: '', redirectTo: 'products', pathMatch: 'full' },
  { path: 'products', component: ProductListComponent },
  { path: 'products/:id', component: ProductDetailsComponent },
  { path: 'create', component: ProductCreateComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 5 : Adding and Styling a Navigation Bar Using Bootstrap 4

Next, let's add Bootstrap 4 to our application and a navigation bar.

We'll be using Bootstrap 4 for styling the UI so you'll need to install it in your project. Check out three ways for how to add bootstrap to your Angular project.

Open the src/app/app.component.html file, and update as follows:

<div>
  <nav class="navbar navbar-expand navbar-dark bg-dark">
    <a href="#" class="navbar-brand">Techiediaries</a>
    <div class="navbar-nav mr-auto">
      <li class="nav-item">
        <a routerLink="products" class="nav-link">Products</a>
      </li>
      <li class="nav-item">
        <a routerLink="create" class="nav-link">Create</a>
      </li>
    </div>
  </nav>

  <div class="container mt-5">
    <router-outlet></router-outlet>
  </div>
</div>

We have created a bootstrap navigation bar and wrapped the router outlet with a container div.

Step 6 : Creating an Angular 11 CRUD Service

Next, we need to create a CRUD service that will use Angular 11 HTTPClient to send HTTP requests to the REST API server.

Open the src/services/product.service.ts file and update it as follows:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

const baseURL = 'http://localhost:8080/api/products';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private httpClient: HttpClient) { }

  readAll(): Observable<any> {
    return this.httpClient.get(baseURL);
  }

  read(id): Observable<any> {
    return this.httpClient.get(`${baseURL}/${id}`);
  }

  create(data): Observable<any> {
    return this.httpClient.post(baseURL, data);
  }

  update(id, data): Observable<any> {
    return this.httpClient.put(`${baseURL}/${id}`, data);
  }

  delete(id): Observable<any> {
    return this.httpClient.delete(`${baseURL}/${id}`);
  }

  deleteAll(): Observable<any> {
    return this.httpClient.delete(baseURL);
  }

  searchByName(name): Observable<any> {
    return this.httpClient.get(`${baseURL}?name=${name}`);
  }
}

Step 7 : Implementing the Angular 11 CRUD Components

We have previously generated three components and added them to the router, let's now implement the actual functionality of each component.

Creating a New Product Component

This component provides a form for submitting a new product with two fields, name and description. It injects and calls the ProductService.create() method.

Open the src/components/product-create/product-create.component.ts file and update it as follows:

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';

@Component({
  selector: 'app-product-create',
  templateUrl: './product-create.component.html',
  styleUrls: ['./product-create.component.css']
})
export class ProductCreateComponent implements OnInit {
  product = {
    name: '',
    description: '',
    available: false
  };
  submitted = false;

  constructor(private productService: ProductService) { }

  ngOnInit(): void {
  }

  createProduct(): void {
    const data = {
      name: this.product.name,
      description: this.product.description
    };

    this.productService.create(data)
      .subscribe(
        response => {
          console.log(response);
          this.submitted = true;
        },
        error => {
          console.log(error);
        });
  }

  newProduct(): void {
    this.submitted = false;
    this.product = {
      name: '',
      description: '',
      available: false
    };
  }

}

Next, open the src/components/product-create/product-create.component.html file and update it as follows:

<div style="width: 500px; margin: auto;">
  <div class="submit-form">
    <div *ngIf="!submitted">
      <div class="form-group">
        <label for="name">Name</label>
        <input
          type="text"
          class="form-control"
          id="name"
          required
          [(ngModel)]="product.name"
          name="name"
        />
      </div>

      <div class="form-group">
        <label for="description">Description</label>
        <input
          class="form-control"
          id="description"
          required
          [(ngModel)]="product.description"
          name="description"
        />
      </div>

      <button (click)="createProduct()" class="btn btn-success">Create</button>
    </div>

    <div *ngIf="submitted">
      <h3>You successfully created a product!</h3>
      <button class="btn btn-success" (click)="newProduct()">New..</button>
    </div>
  </div>
</div>

Displaying the List of Products Component

Next, let's implement the product list component, which makes use of the following service methods:

  • readAll()
  • deleteAll()
  • searchByName()

Open the src/components/product-list/product-list.component.ts file and update it as follows:

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {

  products: any;
  currentProduct = null;
  currentIndex = -1;
  name = '';

  constructor(private productService: ProductService) { }

  ngOnInit(): void {
    this.readProducts();
  }

  readProducts(): void {
    this.productService.readAll()
      .subscribe(
        products => {
          this.products = products;
          console.log(products);
        },
        error => {
          console.log(error);
        });
  }

  refresh(): void {
    this.readProducts();
    this.currentProduct = null;
    this.currentIndex = -1;
  }

  setCurrentProduct(product, index): void {
    this.currentProduct = product;
    this.currentIndex = index;
  }

  deleteAllProducts(): void {
    this.productService.deleteAll()
      .subscribe(
        response => {
          console.log(response);
          this.readProducts();
        },
        error => {
          console.log(error);
        });
  }

  searchByName(): void {
    this.productService.searchByName(this.name)
      .subscribe(
        products => {
          this.products = products;
          console.log(products);
        },
        error => {
          console.log(error);
        });
  }
}

Open the src/components/product-list/product-list.component.html file and update it as follows:

<div class="list row">
  <div class="col-md-8">
    <div class="input-group mb-4">
      <input
        type="text"
        class="form-control"
        placeholder="Search by name"
        [(ngModel)]="name"
      />
      <div class="input-group-append">
        <button
          class="btn btn-outline-secondary"
          type="button"
          (click)="searchByName()"
        >
          Search
        </button>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <h4>Product List</h4>
    <ul class="list-group">
      <li
        class="list-group-item"
        *ngFor="let product of products; let i = index"
        [class.active]="i == currentIndex"
        (click)="setCurrentProduct(product, i)"
      >

      </li>
    </ul>

    <button class="m-4 btn btn-sm btn-danger" (click)="deleteAllProducts()">
      Delete All
    </button>
  </div>
  <div class="col-md-6">
    <div *ngIf="currentProduct">
      <h4>Product</h4>
      <div>
        <label><strong>Name:</strong></label> 
      </div>
      <div>
        <label><strong>Description:</strong></label>

      </div>
      <div>
        <label><strong>Status:</strong></label>

      </div>

      <a class="badge badge-warning" routerLink="/products/">
        Edit
      </a>
    </div>

    <div *ngIf="!currentProduct">
      <br />
      <p>Please click on a product</p>
    </div>
  </div>
</div>

If you click on Edit button of any product, you will be directed to the product details page with the /products/:id URL.

The Product Details Component

Next, let's implement the product details component of our Angular 11 CRUD application.

Open the src/components/product-details/product-details.component.ts file and update it as follows:

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {
  currentproduct = null;
  message = '';

  constructor(
    private productService: ProductService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit(): void {
    this.message = '';
    this.getProduct(this.route.snapshot.paramMap.get('id'));
  }

  getProduct(id): void {
    this.productService.read(id)
      .subscribe(
        product => {
          this.currentProduct = product;
          console.log(product);
        },
        error => {
          console.log(error);
        });
  }

  setAvailableStatus(status): void {
    const data = {
      name: this.currentProduct.name,
      description: this.currentProduct.description,
      available: status
    };

    this.productService.update(this.currentProduct.id, data)
      .subscribe(
        response => {
          this.currentProduct.available = status;
          console.log(response);
        },
        error => {
          console.log(error);
        });
  }

  updateProduct(): void {
    this.productService.update(this.currentProduct.id, this.currentProduct)
      .subscribe(
        response => {
          console.log(response);
          this.message = 'The product was updated!';
        },
        error => {
          console.log(error);
        });
  }

  deleteProduct(): void {
    this.productService.delete(this.currentProduct.id)
      .subscribe(
        response => {
          console.log(response);
          this.router.navigate(['/products']);
        },
        error => {
          console.log(error);
        });
  }
}

Open the src/components/product-details/product-details.component.html file and update it as follows:

<div style="width: 500px; margin: auto;">
  <div *ngIf="currentProduct" class="edit-form">
    <h4>Product</h4>
    <form>
      <div class="form-group">
        <label for="title">Name</label>
        <input
          type="text"
          class="form-control"
          id="name"
          [(ngModel)]="currentProduct.name"
          name="name"
        />
      </div>
      <div class="form-group">
        <label for="description">Description</label>
        <input
          type="text"
          class="form-control"
          id="description"
          [(ngModel)]="currentProduct.description"
          name="description"
        />
      </div>

      <div class="form-group">
        <label><strong>Status:</strong></label>

      </div>
    </form>

    <button
      class="badge badge-primary mr-2"
      *ngIf="currentProduct.available"
      (click)="setAvailableStatus(false)"
    >
      Set Not Available
    </button>
    <button
      *ngIf="!currentProduct.available"
      class="badge badge-primary mr-2"
      (click)="setAvailableStatus(true)"
    >
      Set Available
    </button>

    <button class="badge badge-danger mr-2" (click)="deleteProduct()">
      Delete
    </button>

    <button
      type="submit"
      class="badge badge-success"
      (click)="updateProduct()"
    >
      Update
    </button>
    <p></p>
  </div>

  <div *ngIf="!currentProduct">
    <br />
    <p>This product is not accessible</p>
  </div>
</div>

Step 8 : Serving the Angular 11 CRUD App

Head back to your command-line interface, make sure your are navigated at the root of your project's directory and run the following command to start a live development server in your local machine:

$ cd Angular11CRUDExample
$ ng serve    

Go to your web browser and navigate to the http://localhost:4200/ address to start testing your app.

In this tutorial, we’ve built an Angular 11 CRUD application for a Web REST API and we used Bootstrap 4 for styling the UI.

Happy Coding !!!

#angular #angular-11 #bootstrap 4

Gunjan  Khaitan

Gunjan Khaitan

1601500740

Angular Tutorial | Angular Bootstrap | Using Bootstrap With Angular

In this video on Angular Bootstrap, we learn all about Bootstrap, how to embed it in an Angular application to create interactive webpages. Bootstrap is a powerful toolkit - a collection of HTML, CSS, and JavaScript tools for creating and building responsive web pages and web applications. Here’s a list of topics covered -

  • What is Bootstrap?
  • Embedding Bootstrap into Angular
  • Demo - Creating an Application With Angular Bootstrap

#angular #bootstrap #css #web-development #programming