File

src/app/crud/dataset/dataset.component.ts

Implements

OnInit

Metadata

Index

Properties
Methods

Constructor

constructor(route: ActivatedRoute, db: DbConnectionService, querries: QueryService, image: ImageService)
Parameters :
Name Type Optional
route ActivatedRoute No
db DbConnectionService No
querries QueryService No
image ImageService No

Methods

deleteEntry
deleteEntry(PK: object)
Parameters :
Name Type Optional
PK object No
Returns : void
extractPK
extractPK(e: object)
Parameters :
Name Type Optional
e object No
Returns : object
ngOnInit
ngOnInit()
Returns : void
showError
showError(err: string)
Parameters :
Name Type Optional
err string No
Returns : void
showWarning
showWarning(warning: string)
Parameters :
Name Type Optional
warning string No
Returns : void

Properties

dataset
entries
Type : Object[]
entryHeaders
Type : string[]
entryLimit
Type : number
Default value : 100
error
Type : string
filteredEntries
Default value : () => {...}
formurl
Type : string
Default value : "/crud/form"
Public image
Type : ImageService
loading
Type : boolean
searchCol
Type : number
Default value : -1
searchTerm
Type : string
title
Type : string
type
Type : string
warning
Type : string
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ImageService } from 'src/app/image.service';
import { DbConnectionService } from '../../db-connection.service';
import { QueryService } from '../query.service';

@Component({
  selector: 'app-dataset',
  templateUrl: './dataset.component.html',
  styleUrls: ['./dataset.component.scss']
})
export class DatasetComponent implements OnInit {
  formurl = "/crud/form";

  title: string;
  loading: boolean;
  dataset;
  entries: Object[];
  entryHeaders: string[];
  error: string;
  warning: string;
  type: string;

  searchTerm: string;
  searchCol: number = -1;

  entryLimit: number = 100;

  constructor(
    private route: ActivatedRoute,
    private db: DbConnectionService,
    private querries: QueryService,
    public image: ImageService
  ) {
  }

  // lambda function that filters entries using the searchTerm and searchCol variables (searchCol = -1 means filter over all columns)
  filteredEntries = () => {
    return this.entries.filter(u => this.searchCol < 0
      ? (Object.values(u).join().toString().toLowerCase().indexOf(this.searchTerm.toString().toLowerCase()) > -1)
      : (u[this.entryHeaders[this.searchCol]] && u[this.entryHeaders[this.searchCol]].toString().toLowerCase().indexOf(this.searchTerm.toString().toLowerCase()) > -1)
    )
  }

  ngOnInit(){
    this.route.params.subscribe((params) => {
      // restore default variables
      this.error = "";
      this.title = "Loading...";
      this.entries = [];
      this.entryHeaders = [];
      this.loading = true;
      this.searchTerm = "";
      this.searchCol = -1;

      // invalid type
      if (!params.type || !(params.type in this.querries.datasets))
        return this.showError("Unkown dataset '" + params.type + "'");
      this.type = params.type;
      this.dataset = this.querries.datasets[params.type]
      this.db.executeQuery(this.dataset['query']).then(d => {
        // database error
        if (d['error'])
          return this.showError(d['error'])
        // query didn't match any data
        if (!d['data'] || d['data'].length === 0)
          return this.showWarning(`Didn't receive any data`)
        // save data
        this.entries = d['data'];
        this.entryHeaders = Object.keys(this.entries[0]);
        this.loading = false;
        this.title = this.type
      });
    })
  }

  showError(err: string){
    this.title = "ERROR"
    this.error = err;
    this.loading = false;
  }

  showWarning(warning: string){
    this.warning = warning;
    this.loading = false;
    this.title = this.type
  }

  deleteEntry(PK: object){
    this.querries.deleteEntry(PK, this.dataset.tableName).then((r) => {
      //database error
      if (r['error'])
        return this.showError(r['error'])
      // checks if database was affected, then deletes entry locally
      if (r['data']['affectedRows'] === 1)
        this.entries = this.entries.filter(x => !Object.entries(PK).every(([k, v]) => x[k] === v))
      else
        this.showError("Something went wrong")
    })
  }

  // extracts All primary keys from entry
  extractPK(e: object):object{
    let obj = {};
    if (typeof this.dataset.PK !== "object")
      obj[this.dataset.PK] = e[this.dataset.PK]
    else
      this.dataset.PK.forEach(x => {obj[x] = e[x]});
    return obj;
  }
}
<div style="margin: 10px;">
  <h1>{{title}}</h1>
  <div class="input-group mb-3" *ngIf="!loading && !error">
    <button *ngIf="dataset.form && dataset.PK" type="submit" class="btn btn-success" [routerLink]="[formurl, type]">Add new</button>
    <div class="input-group-prepend">
      <span class="input-group-text" id="basic-addon1">🔎</span>
    </div>
    <input type="text" placeholder="Search"  class="form-control" [(ngModel)]="searchTerm">
    <div class="input-group-append">
      <select style="padding-left: 5px;" [(ngModel)]="searchCol">
        <option value="-1" selected>All columns</option>
        <option *ngFor="let h of entryHeaders; let i = index" [value]="i">{{h}}</option>
      </select>
    </div>
  </div>
  <div *ngIf="!loading && !error">
    <div *ngIf="filteredEntries() as ent">
      <p style="margin: 0px;"><i>{{ (ent.length > entryLimit ? "Showing " + entryLimit + " of " : "" ) + ent.length}} results</i></p>
      <div *ngIf="!warning" class="container-fluid">
        <div class="row" >
          <div *ngFor="let h of entryHeaders" class="col" [style]="'border: solid;border-width: 1px'">
            <b>{{ h }}</b>
          </div>
          <div *ngIf="dataset.PK && (dataset.form || dataset.tableName)" class="col" [style]="'border: solid;border-width: 1px'">
            <b>Actions</b>
          </div>
        </div>
        <div *ngFor="let e of ent.slice(0, entryLimit); let i = index" class="row" [style]="'background-color:' + (i%2 === 0 ? '#74ADFF' : '#B5D3FF')">
          <div *ngFor="let h of entryHeaders" class="col" style="border: solid;border-width: 1px;border-top: transparent;">
           <div *ngIf="!image.isImage(e[h])">{{ e[h] }}</div>
           <img *ngIf="image.isImage(e[h])" [src]="e[h]" style="width:200px">
          </div>
          <div *ngIf="dataset.PK && (dataset.form || dataset.tableName)" class="col" style="border: solid;border-width: 1px;border-top: transparent;">
            <div class="btn-group special" role="group" aria-label="..." style="padding:5px;">
              <button *ngIf="dataset.form" type="button" class="btn btn-outline-success" [routerLink]="[formurl, type]" [queryParams]="extractPK(e)">✏️</button>
              <button *ngIf="dataset.tableName" type="button" class="btn btn-outline-danger" (click)="deleteEntry(extractPK(e))">🗑️</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>


  <i *ngIf="error"> {{error}}</i>
  <i *ngIf="warning"> {{warning}}</i>
</div>

./dataset.component.scss

.btn-group.special {
  display: flex;
}

.special .btn {
  flex: 1
}
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""