ANgular List and Drop down

 

Step 1: Setup Angular Service for HTTP Requests

Create a service to handle fetching data from the backend.

ng generate service data

In data.service.ts, implement the necessary HTTP calls to get data.

// data.service.ts

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs';

 

@Injectable({

  providedIn: 'root'

})

export class DataService {

 

  private apiUrl = 'https://your-api-url.com/api';  // Replace with your backend API URL

 

  constructor(private http: HttpClient) { }

 

  // Fetch the list of items (example data for display)

  getItems(): Observable<any[]> {

    return this.http.get<any[]>(`${this.apiUrl}/items`);

  }

 

  // Fetch dropdown data for first dropdown (Example: categories)

  getDropdown1Data(): Observable<any[]> {

    return this.http.get<any[]>(`${this.apiUrl}/dropdown1`);

  }

 

  // Fetch dropdown data for second dropdown (Example: brands)

  getDropdown2Data(): Observable<any[]> {

    return this.http.get<any[]>(`${this.apiUrl}/dropdown2`);

  }

 

  // Save edited data (optional, if you want to post the form data back to backend)

  saveItem(data: any): Observable<any> {

    return this.http.put<any>(`${this.apiUrl}/items/${data.id}`, data);

  }

}

Step 2: Display List of Items with Edit Option

We will use a table to display the list of items, and each item will have an "Edit" button that will open a form.

Create a component to display the list:

ng generate component item-list

In item-list.component.ts, fetch and display the list of items:

// item-list.component.ts

import { Component, OnInit } from '@angular/core';

import { DataService } from '../data.service';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';  // For modal dialog to edit data (optional)

 

@Component({

  selector: 'app-item-list',

  templateUrl: './item-list.component.html',

  styleUrls: ['./item-list.component.css']

})

export class ItemListComponent implements OnInit {

  items: any[] = [];  // List of items

  selectedItem: any = null;  // Store selected item for editing

 

  constructor(private dataService: DataService, private modalService: NgbModal) { }

 

  ngOnInit(): void {

    this.loadItems();  // Load items when component initializes

  }

 

  loadItems(): void {

    this.dataService.getItems().subscribe(data => {

      this.items = data;  // Store the fetched items in the component variable

    });

  }

 

  openEditModal(content: any, item: any): void {

    this.selectedItem = { ...item };  // Create a copy of the item to be edited

    this.modalService.open(content);  // Open the modal to edit

  }

}

In item-list.component.html, display the list in a table with an "Edit" button:

<!-- item-list.component.html -->

<div class="container">

  <h2>Items List</h2>

  <table class="table table-bordered">

    <thead>

      <tr>

        <th>ID</th>

        <th>Name</th>

        <th>Actions</th>

      </tr>

    </thead>

    <tbody>

      <tr *ngFor="let item of items">

        <td>{{ item.id }}</td>

        <td>{{ item.name }}</td>

        <td><button class="btn btn-primary" (click)="openEditModal(editModal, item)">Edit</button></td>

      </tr>

    </tbody>

  </table>

</div>

 

<!-- Modal for editing item -->

<ng-template #editModal let-modal>

  <div class="modal-header">

    <h4 class="modal-title">Edit Item</h4>

    <button type="button" class="close

    " (click)="modal.dismiss()" aria-label="Close">

      <span aria-hidden="true">&times;</span>

    </button>

  </div>

  <div class="modal-body">

    <form (ngSubmit)="saveItem()">

      <div class="form-group">

        <label for="itemName">Item Name</label>

        <input type="text" id="itemName" class="form-control" [(ngModel)]="selectedItem.name" name="name" required />

      </div>

 

      <!-- Dropdown 1 -->

      <div class="form-group">

        <label for="dropdown1">Select Category</label>

        <select id="dropdown1" class="form-control" [(ngModel)]="selectedItem.category" name="category" required>

          <option *ngFor="let option of dropdown1Data" [value]="option.id">{{ option.name }}</option>

        </select>

      </div>

 

      <!-- Dropdown 2 -->

      <div class="form-group">

        <label for="dropdown2">Select Brand</label>

        <select id="dropdown2" class="form-control" [(ngModel)]="selectedItem.brand" name="brand" required>

          <option *ngFor="let option of dropdown2Data" [value]="option.id">{{ option.name }}</option>

        </select>

      </div>

 

      <button type="submit" class="btn btn-success">Save</button>

    </form>

  </div>

</ng-template>

Step 3: Handle Data Fetch for Dropdowns in Component

Next, in item-list.component.ts, we need to fetch the data for the dropdowns when the modal opens.

// item-list.component.ts

import { Component, OnInit } from '@angular/core';

import { DataService } from '../data.service';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

 

@Component({

  selector: 'app-item-list',

  templateUrl: './item-list.component.html',

  styleUrls: ['./item-list.component.css']

})

export class ItemListComponent implements OnInit {

  items: any[] = [];  // List of items

  selectedItem: any = null;  // Store selected item for editing

  dropdown1Data: any[] = [];  // Data for dropdown 1

  dropdown2Data: any[] = [];  // Data for dropdown 2

 

  constructor(private dataService: DataService, private modalService: NgbModal) { }

 

  ngOnInit(): void {

    this.loadItems();  // Load items when component initializes

    this.loadDropdownData();  // Load dropdown data when component initializes

  }

 

  loadItems(): void {

    this.dataService.getItems().subscribe(data => {

      this.items = data;  // Store the fetched items in the component variable

    });

  }

 

  loadDropdownData(): void {

    this.dataService.getDropdown1Data().subscribe(data => {

      this.dropdown1Data = data;  // Store the dropdown 1 data

    });

 

    this.dataService.getDropdown2Data().subscribe(data => {

      this.dropdown2Data = data;  // Store the dropdown 2 data

    });

  }

 

  openEditModal(content: any, item: any): void {

    this.selectedItem = { ...item };  // Create a copy of the item to be edited

    this.modalService.open(content);  // Open the modal to edit

  }

 

  saveItem(): void {

    this.dataService.saveItem(this.selectedItem).subscribe(updatedItem => {

      // Update the item in the list with the updated item returned from the backend

      const index = this.items.findIndex(item => item.id === updatedItem.id);

      if (index !== -1) {

        this.items[index] = updatedItem;  // Replace the updated item in the list

      }

      // Close the modal

      this.modalService.dismissAll();

    });

  }

}

Step 4: Using Bootstrap Modal for Form Popup

To open a modal with the form for editing, we use ng-bootstrap (which is a Bootstrap library for Angular). If you don’t have it installed already, install it by running:

npm install @ng-bootstrap/ng-bootstrap

Then, import the required modules in app.module.ts:

// app.module.ts

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

 

@NgModule({

  declarations: [

    AppComponent,

    ItemListComponent

  ],

  imports: [

    BrowserModule,

    HttpClientModule,

    NgbModule  // Import NgbModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

Final Outcome

  • Item List: When you click the "Edit" button, it will open a modal form to edit the item.
  • Dropdowns: The form contains two dropdowns populated with data fetched from the backend using HTTP requests.
  • Editing and Saving: You can edit the item and save it back to the backend. The updated data will be reflected in the list.

Notes:

  • The form uses ngModel for two-way data binding, so when the form is edited, it updates the selectedItem in the component.
  • The NgbModal is used to show the modal with the form, which makes it easy to handle popups in Angular.
  • HTTP requests are handled by the DataService using the Angular HTTP client.

This approach keeps the Angular code separate from the backend logic and ensures that your frontend can interact with the backend API seamlessly.

 

To implement the functionality described in your Angular app using a .NET Core Web API, here's a breakdown of how to set up the backend. The objective is to create endpoints to handle data fetching, item editing, and dropdown data population for the front-end to interact with.

Step 1: Set Up .NET Core Web API

First, create a new .NET Core Web API project:

dotnet new webapi -n SharedDataApi

Navigate to the project folder:

cd SharedDataApi

Step 2: Define Data Models

Create models for the items and dropdown data. This helps define the structure of the data you'll be sending and receiving from the API.

Models/Item.cs:

namespace SharedDataApi.Models

{

    public class Item

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public int CategoryId { get; set; }

        public int BrandId { get; set; }

    }

}

Models/DropdownItem.cs:

namespace SharedDataApi.Models

{

    public class DropdownItem

    {

        public int Id { get; set; }

        public string Name { get; set; }

    }

}

Step 3: Create Data Service

Next, create a service to manage the data for items and dropdowns.

Services/IDataService.cs:

using SharedDataApi.Models;

using System.Collections.Generic;

 

namespace SharedDataApi.Services

{

    public interface IDataService

    {

        List<Item> GetItems();

        List<DropdownItem> GetDropdown1Data();

        List<DropdownItem> GetDropdown2Data();

        Item SaveItem(Item item);

    }

}

Services/DataService.cs:

using SharedDataApi.Models;

using System.Collections.Generic;

using System.Linq;

 

namespace SharedDataApi.Services

{

    public class DataService : IDataService

    {

        private readonly List<Item> _items;

        private readonly List<DropdownItem> _dropdown1Data;

        private readonly List<DropdownItem> _dropdown2Data;

 

        public DataService()

        {

            // Sample Data

            _items = new List<Item>

            {

                new Item { Id = 1, Name = "Item 1", CategoryId = 1, BrandId = 1 },

                new Item { Id = 2, Name = "Item 2", CategoryId = 2, BrandId = 2 }

            };

 

            _dropdown1Data = new List<DropdownItem>

            {

                new DropdownItem { Id = 1, Name = "Category 1" },

                new DropdownItem { Id = 2, Name = "Category 2" }

            };

 

            _dropdown2Data = new List<DropdownItem>

            {

                new DropdownItem { Id = 1, Name = "Brand 1" },

                new DropdownItem { Id = 2, Name = "Brand 2" }

            };

        }

 

        public List<Item> GetItems()

        {

            return _items;

        }

 

        public List<DropdownItem> GetDropdown1Data()

        {

            return _dropdown1Data;

        }

 

        public List<DropdownItem> GetDropdown2Data()

        {

            return _dropdown2Data;

        }

 

        public Item SaveItem(Item item)

        {

            var existingItem = _items.FirstOrDefault(i => i.Id == item.Id);

            if (existingItem != null)

            {

                existingItem.Name = item.Name;

                existingItem.CategoryId = item.CategoryId;

                existingItem.BrandId = item.BrandId;

            }

            else

            {

                _items.Add(item);

            }

 

            return item;

        }

    }

}

Step 4: Register Services

Register the data service in Startup.cs (or Program.cs for .NET 6+).

Program.cs (for .NET 6 and beyond):

using Microsoft.AspNetCore.Builder;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

using SharedDataApi.Services;

 

var builder = WebApplication.CreateBuilder(args);

 

builder.Services.AddSingleton<IDataService, DataService>();

builder.Services.AddControllers();

 

var app = builder.Build();

 

app.UseAuthorization();

app.MapControllers();

 

app.Run();

Step 5: Create API Controller

Create a controller to handle HTTP requests for getting items, dropdown data, and saving items.

Controllers/SharedDataController.cs:

using Microsoft.AspNetCore.Mvc;

using SharedDataApi.Models;

using SharedDataApi.Services;

 

namespace SharedDataApi.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class SharedDataController : ControllerBase

    {

        private readonly IDataService _dataService;

 

        public SharedDataController(IDataService dataService)

        {

            _dataService = dataService;

        }

 

        // Get all items

        [HttpGet("items")]

        public ActionResult<IEnumerable<Item>> GetItems()

        {

            return Ok(_dataService.GetItems());

        }

 

        // Get dropdown 1 data

        [HttpGet("dropdown1")]

        public ActionResult<IEnumerable<DropdownItem>> GetDropdown1Data()

        {

            return Ok(_dataService.GetDropdown1Data());

        }

 

        // Get dropdown 2 data

        [HttpGet("dropdown2")]

        public ActionResult<IEnumerable<DropdownItem>> GetDropdown2Data()

        {

            return Ok(_dataService.GetDropdown2Data());

        }

 

        // Save or edit an item

        [HttpPut("items/{id}")]

        public ActionResult<Item> SaveItem(int id, [FromBody] Item item)

        {

            if (item.Id != id)

                return BadRequest("Item ID mismatch");

 

            var updatedItem = _dataService.SaveItem(item);

            return Ok(updatedItem);

        }

    }

}

Step 6: Test the API Endpoints

You can test the API endpoints using tools like Postman or cURL. Here's how the endpoints should work:

  • GET http://localhost:5000/api/shareddata/items → Fetch the list of items.
  • GET http://localhost:5000/api/shareddata/dropdown1 → Fetch data for the first dropdown.
  • GET http://localhost:5000/api/shareddata/dropdown2 → Fetch data for the second dropdown.
  • PUT http://localhost:5000/api/shareddata/items/{id} → Update an item with the given ID.

Conclusion

In this .NET Core Web API:

  1. IDataService manages the items and dropdown data.
  2. DataService implements the service logic for fetching items and dropdown data and saving updated items.
  3. The API controller handles the HTTP requests for fetching the data and updating the items.

On the Angular side, you would interact with this API via HTTP calls, where the front-end makes requests to get the list of items, dropdown data, and save edited items. This architecture ensures that the data flow between the client and server is seamless and structured.

 


Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced