Angular Material Select and database lookup tables (referential integrity)

This article is an addition to the video below, and it demonstrates how to use “lookup tables” from your database, and combine these with Angular Material Select widgets. The specific table I am wrapping, is the “account_types” table from the “magic_crm” MySQL database, but the idea is similar for all lookup tables. You might have to use a different [value] for your “mat-option” elements, if the primary key in your lookup table is not the same as the display column.

Above is how our final result will look like. Notice the Material Select dropdown parts.

In the following video, I am walking you through all the required steps to create the above result.

Walkthrough of how to use Material Select to ensure and simplify database referential integrity

The HTML code I created for the above video was as follows. Notice, this code should replace your existing “mat-form-field” wrapping your input data-bound towards “data.entity.account_type” in your “accounts-edit-modal.html” file. Delete that entire mat-form-field, and paste in the following code as its replacement.

  <mat-form-field
    class="entity-edit-field">
    <mat-select
      matInput
      placeholder="Account type"
      [(ngModel)]="data.entity.account_type">
      <mat-option
        *ngFor="let el of accountTypes"
        [value]="el.name">{{el.name}}</mat-option>
    </mat-select>
  </mat-form-field>

Replace the existing “account_type” input widget with the code from above. Then import OnInit with the following import declaration in your “accounts-edit-modal.ts” file. Basically, just add “OnInit” into your list of imports from “@angular/core”.

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

Make sure you implement OnInit on your component. This interface ensures Angular invokes your “ngOnInit” method as the component is initially loaded by Angular.

export class AccountsEditModalComponent implements OnInit {

Add a field in your class to hold your “account_types”. This becomes our “data source” for our Angular Material Select widget.

private accountTypes: any[] = [];

And implement the ngOnInit method in your TypeScript file. This method retrieves all “account_types” from your backend, and assigns them to the field we created in the above code. The rest will be automagically wrapped up by Angular and Magic in combination.

  ngOnInit() {
    this.service.account_typesGet({}).subscribe(res => {
      this.accountTypes = res;
    });
  }

If you’re still confused, please watch the video above where I demonstrate the process in 10 minutes.

Notice, I want to emphasise that this is useful for database tables with maybe 5-50 items, and it is *not* for tables having hundreds or thousands of records!

Resources

Published by servergardens

Create .Net Core CRUD APIs wrapping your SQL database in seconds