how to create dynamic row in a table javascript angular 2 - javascript

I am creating a table based on dropdown selection. I am able to display the data for a single selection. I want to create a function for "new button" which will add a row and selected value will be display in new generated row. how can I achieve this using javascript or angular 2.
P.S.I am just a beginner. thanks in advance.
Screenshot
import { NgModule } from '#angular/core';
import { Component, OnInit } from '#angular/core';
import {SelectItem} from 'primeng/primeng';
import { FormsModule } from '#angular/forms';
import {ButtonModule} from 'primeng/primeng';
import {DataTableModule,SharedModule} from 'primeng/primeng';
#Component({
selector: 'app-test',
templateUrl: 'app/test/test.component.html',
styleUrls: ['app/test/test.component.css']
})
export class TestComponent implements OnInit {
makes: SelectItem[];
selectedMake: string;
motors: SelectItem[];
selectedMotorType: string;
poles: SelectItem[];
selectedPole: string;
}
constructor() {
this.makes = [];
this.makes.push({label:'Select makes', value:null});
this.makes.push({label:'Siemens', value:{id:1, name: 'Siemens', code: 'Siemens'}});
this.makes.push({label:'ABS', value:{id:2, name: 'ABS', code: 'ABS'}});
this.motors = [];
this.motors.push({label:'Select Motor Type', value:null});
this.motors.push({label:'IE1', value:{id:11, name: 'IE1', code: 'IE1'}});
this.motors.push({label:'IE2', value:{id:12, name: 'IE2', code: 'IE2'}});
this.motors.push({label:'IE3', value:{id:13, name: 'IE3', code: 'IE3'}});
this.poles = [];
this.poles.push({label:'Select Pole Type', value:null});
this.poles.push({label:'2 Pole', value:{id:21, name: '2Pole', code: '2Pole'}});
this.poles.push({label:'4 Pole', value:{id:22, name: '4Pole', code: '4Pole'}});
this.poles.push({label:'6 Pole', value:{id:23, name: '6Pole', code: '6Pole'}});
}
//code for button click new row generate
rows = [{name: ''}];
name = "new";
addRow() {
this.rows.push({name: this.name});
}
//=================
private textValue = "initial value";
private log: string ='result';
private kw: string = 'kw';
private frame: number = 0;
DisplayResult(){
if(this.selectedMake.name=='ABS' && this.selectedMotorType.name=='IE1' ){
alert(this.selectedMake.name);
this.log = 'IABVC5Z' '\n'
this.kw = 'new' '\n'
}}
<div class="container row">
<div class="col-sm-6">
<p class="col-sm-3" >Makes :</p>
<p-dropdown class="col-sm-4" [options]="makes" [(ngModel)]="selectedMake" [style]="{'width':'200px'}" ></p-dropdown>
</div>
</div>
<br>
<div class="container row">
<div class="col-sm-6">
<p class="col-sm-3" >Motor Type :</p>
<p-dropdown class="col-sm-4" [options]="motors" [(ngModel)]="selectedMotorType" [style]="{'width':'200px'}" ></p-dropdown>
</div>
</div>
<br>
<div class="container row">
<div class="col-sm-6">
<p class="col-sm-3" >Pole Type :</p>
<p-dropdown class="col-sm-4" [options]="poles" [(ngModel)]="selectedPole" [style]="{'width':'200px'}" ></p-dropdown>
</div>
</div>
<div class="col-sm-4">
<button class="" pButton type="button" class="ui-button-danger" (click)="addRow()" label = " Add New Motor"></button>
<button class="" pButton type="button" (click)="DisplayResult()" label="Display Result"></button>
</div>
<table id="t01">
<tr>
<th>S.No.</th>
<th>Qty</th>
<th>Type Refrence</th>
<th>KW Rating</th>
<th>Frame Size</th>
<th>Voltage</th>
<th>Frequency</th>
<th>Features</th>
</tr>
<tr *ngFor=" let row of rows">
<td>1</td>
<td><input type="qty" name="qty"></td>
<td>{{log}}</td>
<td>{{kw}}</td>
<td>{{frame}}</td>
<td>415 v</td>
<td>50 Hz</td>
<td></td>
</tr>
</table>

All you need to do is write a function/method inside the component and then call that function/method in the click event if you select the add button
#Component({...})
export class TestComponent {
addRow() {
this.rows.push({
make : this.make,
model: this.model,
pole: this.pole
});
}
The addRow fires when the button is clicked
<button class="" pButton type="button" class="ui-button-danger" (click)="addRow()" label = " Add New Motor">Add New Motor</button>
I also added text between the button tags for display. You must update your table to select the appropriate values to display
<table id="t01">
<tr>
<th>S.No.</th>
<th>Qty</th>
<th>Type Refrence</th>
<th>KW Rating</th>
<th>Frame Size</th>
<th>Voltage</th>
<th>Frequency</th>
<th>Features</th>
</tr>
<tr *ngFor=" let row of rows">
<td>{{ row.make.name }}</td>
<td><input type="qty" name="qty" [row.model]></td>
<td>{{ row.model.log }}</td>
<td>{{ row.model.kw}}</td>
<td>{{ row.model.frame }}</td>
<td>{{ row.model.somethingElse }}</td>
<td>{{ row.pole.simething }}</td>
<td>{{ row.pole.etc }}</td>
</tr>
</table>
I didn't know your data, so just us m selected values from random fields, but that is how you would typically do that

Related

filter via a drop-down list in Angular

Here is a small illustration of my problem.
I have an HTML table with elements and a drop down list
enter image description here
If the user clicks on in, all records with type in are displayed
enter image description here
I don't know how to do it but while searching the internet I came across this page.
When I select in, my HTML table becomes empty, it doesn't fetch the record.
Do you know why?
service.ts
#Injectable({
providedIn: 'root'
})
export class CorporateActionService {
startDate = new Date("");
prea = [{
num: "758-1184511-34",
svm: "000902988",
type: "in",
quantity: "12,00",
isin: "BE0003470755",
title: "SOLVAY BE",
},
{
num: "758-1184511-34",
svm: "000902987",
type: "out",
quantity: "11,25",
isin: "BE0152676954",
title: "AXA B FD EQUITY BELGIUM",
},
]
dataList = [{
code: 1,
name: "in"
},
{
code: 2,
name: "out"
},
]
constructor() {}
}
component.ts
export class CorporateActionComponent implements OnInit {
prea: any;
dataList: any;
brandName = {};
constructor(private service: CorporateActionService) {}
ngOnInit(): void {
this.prea = this.service.prea;
this.dataList = this.service.dataList;
this.brandName = this.dataList.brandName;
}
public selectedBrand: any;
public valueSelected() {
this.prea = this.service.prea.filter(
item => item.num === this.selectedBrand
);
}
}
component.html
<div class="home-content container ">
<h1 class="text-center pt-5 pb-3">Corporate Action</h1>
<div class="row pt-3 container">
<div class="card" style="width: 100%;">
<div class="card-body">
<div class="text-end">
<select [(ngModel)]="selectedBrand" (change)="valueSelected()">
<option>Select</option>
<option *ngFor="let item of dataList;let i = index" value="{{item.code}}" [selected]="i == 0">
{{item.name}}
</option>
</select>
</div>
<table class="table table-striped table-hover">
<thead class="thead-light">
<tr class="text-center">
<th scope="col">Client</th>
<th scope="col">N° de préavis</th>
<th scope="col">Type</th>
<th scope="col">Quantité</th>
<th scope="col">ISIN</th>
<th scope="col">Titre</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let line of prea">
<td scope="row" class="text-center">{{ line.num }}</td>
<td scope="row" class="text-center">{{ line.svm }}</td>
<td scope="row" class="text-center">{{ line.type }}</td>
<td scope="row" class="text-center">{{ line.quantity }}</td>
<td scope="row" class="text-center">{{ line.isin }}</td>
<td scope="row" class="text-center">{{ line.title }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
Here is a reproduction.
Two things:
Change the value of the options to item.name since that's how you identify them
<option *ngFor="let item of dataList;let i = index" value="{{item.name}}" [selected]="i == 0">
And filter the array by type since that's where your in and out properties are.
public valueSelected() {
this.prea = this.service.prea.filter(
(item) => item.type === this.selectedBrand
);
}
https://stackblitz.com/edit/github-jvrg8t-npq79e?file=src/app/views/dashboard/views/administration/views/corporate-action/corporate-action.component.ts

Validation of HTML table cell and changing background color using Javascript

This is HTML table and I want to validate it in such a way that if user clears entry, the background color of particular cell should be turned red. Code for model should be in JavaScript or Typescript. Please don't provide jQuery solutions
app.component.html
<table class="material-table">
<thead>
<tr>
<th></th>
<!-- <th *ngFor="let schema of tableSchema">
{{ schema.field }}
</th> -->
</tr>
</thead>
<tr *ngFor="let rowData of tableData">
<td value="Delete" (click)="deleteRow(rowData)">X</td>
<td
*ngFor="let schema of tableSchema"
[class.red-text]="!rowData[schema.field].valid"
>
<span
#el
contenteditable
(blur)="rowData[schema.field].value = el.innerText"
>
{{ rowData[schema.field].value }}
</span>
</td>
</tr>
</table>
You can use Attribute directives:
JS
import { Directive, ElementRef, HostListener, KeyValueDiffers } from '#angular/core';
#Directive({
selector: '[requiredHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
color = "red";
#HostListener('input') onChange() {
this.highlight();
}
private highlight() {
const color = this.el.nativeElement.innerHTML ? null: this.color;
this.el.nativeElement.style.backgroundColor = color;
}
}
HTML Template:
<td *ngFor="let schema of tableSchema">
<span #el contenteditable requiredHighlight (blur)="rowData[schema.field].value = el.innerText" >
{{ rowData[schema.field].value }}
</span>
</td>
Use NgClass.
<td *ngFor="let schema of tableSchema" [ngClass]="{'red-text':!rowData[schema.field].valid}">
<span #el contenteditable (blur)="rowData[schema.field].value = el.innerText">
{{ rowData[schema.field].value }}
</span>
</td>

datatable.net in Angular not recognize the tr inside the table

this is my problem, sometimes the component render the table like this.
(No problems):
(Problem):
In the 2 photo you can see the empty row generated by datatables, it means the datatable not recognize the rows and this implies the datatable options like search or pageLength dont work. What i should do?
This is my table component:
Template:
<div class="table-responsive">
<table datatable [dtOptions]="dtOptions" class="table table-hover" [ngClass]="extraClass" width="100%">
<thead>
<tr>
<th *ngFor="let column of columns">{{ column }}</th>
</tr>
</thead>
<tfoot *ngIf="footer">
<tr>
<th *ngFor="let column of columns">{{ column }}</th>
</tr>
</tfoot>
<tbody>
<ng-content></ng-content>
</tbody>
</table>
</div>
Component:
import { Component, Input, OnChanges, OnInit } from '#angular/core';
import { datatableLanguage } from "../../data/index";
#Component({
selector: 'app-table',
templateUrl: './table.component.html'
})
export class TableComponent implements OnInit, OnChanges {
#Input()
public columns: Array<string>;
#Input()
public extraClass: string;
#Input()
public footer: boolean;
public dtOptions: DataTables.Settings;
constructor() {
this.columns = new Array<string>(0);
this.extraClass = '';
this.footer = true;
this.dtOptions = {};
}
ngOnInit() {
this.checkRequiredFields();
this.dtOptions = {
"language": datatableLanguage,
"responsive": true
}
}
ngOnChanges() {
this.checkRequiredFields();
}
checkRequiredFields(): void {
if(this.columns.length <= 0)
throw new Error("Attribute 'columns' is required.");
}
}
And if you need it, the father component:
Table template part:
<app-table id="ingredientsTable" [columns]="['Nombre', 'Precio/Unidad', 'Cantidad', 'Acciones']" [footer]="ingredients.length >= 10">
<tr [class.table-danger]="ingredient.amount <= 0" *ngFor="let ingredient of ingredients">
<td class="align-middle">{{ ingredient.name }}</td>
<td class="align-middle text-center">{{ ingredient.priceByUnit | number }}</td>
<td class="align-middle text-center">{{ ingredient.amount | number }}</td>
<td>
<div class="text-center">
<div class="btn-group">
<button class="btn btn-info" (click)="changeModal(ingredient)" data-toggle="modal" data-target="#modalIngredients">
<i class="far fa-edit"></i>
</button>
<button class="btn btn-danger" (click)="deleteIngredient(ingredient)">
<i class="far fa-trash-alt"></i>
</button>
</div>
</div>
</td>
</tr>
</app-table>

Laravel VueJs store array from axios request in laravel controller

I have a laravel 5.7 application which uses VueJS 2.0 for the front end.
I have two table with many-to-many relation: commandes and produits.I am currently attempting to pass data in to my commandes table but i am getting this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `commande_produit` (`0`, `commande_id`, `produit_id`) values (3, , 0))
If anyone can tell me how to fix or even point me in the right direction it would be much appreciated.
The html template:
<template>
<div class="container">
<div class="row justify-content-center mt-5" v-if="$gate.isAdminOrVendeur()">
<div class="col-md-12">
<form class="" #submit.prevent="envoyer()" >
<table class="table table-bordered table-striped table-responsive">
<thead class="thead-dark">
<tr>
<th class="col-sm-4">Produit</th>
<th class="col-sm-2">Quantité</th>
<th class="col-sm-2">montant</th>
<th class="col-sm-2">Total</th>
<th class="col-sm-1"></th>
<th class="col-sm-1"></th>
</tr>
</thead>
<tbody>
<tr v-for="(commande, index) in commandes" :key="index">
<td>{{ commande.produit_id }}</td>
<td>{{ commande.quantite }}</td>
<td>{{ commande.montant }} F</td>
<td>{{ (commande.quantite * commande.montant).toFixed(2) }} F</td>
<td><a class="btn btn-info btn-block" #click="modifier(index)">Modifier</a></td>
<td><a class="btn btn-warning btn-block" #click="supprimer(index)">Poubelle</a></td>
</tr>
<tr>
<td colspan="3"></td>
<td><strong> F </strong></td>
<td colspan="2"></td>
</tr>
<tr>
<td>
<div class="form-group">
<select v-model="form.produit_id" name="produit_id" class="form-control">
<option v-for="produit in produits.data" :key="produit.id" v-bind:value="produit.id">{{ produit.designation }}</option>
</select>
</div>
</td>
<td><input type="text" class="form-control" v-model="form.quantite"></td>
<td><input type="text" class="form-control" v-model="form.montant"></td>
<td colspan="3"><a class="btn btn-primary btn-block" #click="ajouter">Ajouter</a></td>
</tr>
</tbody>
<tfoot>
<a class="button btn btn-xs btn-warning" #click="toutPoubelle">Tout à la poubelle</a>
<button class="button btn btn-xs btn-success" type="submit">Valider</button>
</tfoot>
</table>
</form>
<div class="panel panel-danger" v-show="poubelle.length">
<div class="panel-heading">Poubelle</div>
<table class="table table-bordered table-striped table-responsive">
<thead>
<tr>
<th class="col-sm-4">Produit</th>
<th class="col-sm-2">Quantité</th>
<th class="col-sm-2">montant</th>
<th class="col-sm-2">Total</th>
<th class="col-sm-1"></th>
<th class="col-sm-1"></th>
</tr>
</thead>
<tbody>
<tr v-for="(commande, index) in poubelle" :key="index">
<td>{{ commande.produit }}</td>
<td>{{ commande.quantite }}</td>
<td>{{ commande.montant }} F</td>
<td>{{ (commande.quantite * commande.montant).toFixed(2) }} F</td>
<td><a class="btn btn-success btn-block" #click="retablir(index)">Rétablir</a></td>
<td><a class="btn btn-danger btn-block" #click="eliminer(index)">Supprimer</a></td>
</tr>
</tbody>
</table>
<div class="panel-footer">
<div class="btn-group">
<a class="button btn btn-xs btn-success" #click="toutRetablir">Tout rétablir</a>
<a class="button btn btn-xs btn-danger" #click="toutEliminer">Tout supprimer</a>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
My vue instance:
<script>
export default {
data () {
return {
commandes: [],
poubelle: [],
produits: {},
form: new Form({
produit_id : '',
quantite : '',
montant: '',
})
}
},
methods: {
ajouter() {
this.commandes.push({produit_id: this.form.produit_id, quantite: this.form.quantite, montant: this.form.montant});
this.form = {};
this.commandes.sort(ordonner);
},
modifier(index) {
this.form.produit_id = this.commandes[index].produit_id;
this.form.quantite = this.commandes[index].quantite;
this.form.montant = this.commandes[index].montant;
this.commandes.splice(index, 1);
},
supprimer(index) {
this.poubelle.push(this.commandes[index]);
this.commandes.splice(index, 1);
this.poubelle.sort(ordonner);
},
retablir(index) {
this.commandes.push(this.poubelle[index]);
this.poubelle.splice(index, 1);
this.commandes.sort(ordonner);
},
eliminer(index) {
this.poubelle.splice(index, 1);
},
toutPoubelle() {
this.poubelle = this.poubelle.concat(this.commandes);
this.poubelle.sort(ordonner);
this.commandes = [];
},
toutRetablir() {
this.commandes = this.commandes.concat(this.poubelle);
this.commandes.sort(ordonner);
this.poubelle = [];
},
toutEliminer() {
this.poubelle = [];
},
loadProduits(){
//if(this.$gate.isAdminOrComptable()){
axios.get("api/produit").then(({ data }) => (this.produits = data));
//}
},
envoyer() {
axios.post('api/commande', {commande: this.commandes});
this.commandes = [];
},
},
mounted() {
this.loadProduits();
console.log('Component mounted.')
}
}
var ordonner = function (a, b) {
return (a.commande.toUpperCase() > b.commande.toUpperCase())
};
</script>
This is the commandes model:
class Commande extends Model
{
protected $fillable = ['commande'];
public function produits()
{
return $this->belongsToMany('App\Models\Produit');
}
}
and the produits model:
class Produit extends Model
{
protected $fillable = ['designation'];
public function commandes()
{
return $this->belongsToMany('App\Models\Commande');
}
}
the commande controller store() method:
public function store(Request $request)
{
$this->validate($request,[
'commande' => 'required',
]);
$commande = new Commande();
$commande->produits()->attach([$request->commande]);
$commande->save();
}
Several things may not work as expected in your code:
You are trying to attach produits on a non-existing model.
By using new Commande you are just preparing the object Commande and not yet saving it to the database. You can't attach anything on it since it doesn't have an id yet.
Solution: use Create instead of New
The method attach() is not used properly
As per the doc (https://laravel.com/docs/7.x/eloquent-relationships#updating-many-to-many-relationships) attach() is expecting an array of ids. You are trying to pass a custom array so the method won't work.
Solution: extract the Ids from your $request->command and then use attach()
Her is the final store() function:
public function store(Request $request)
{
$this->validate($request,[
'commande' => 'required',
]);
$commande = new Commande();
$commande->save();
$produitsId = array_column($request->commande, 'produit_id');
$commande->produits()->attach($produitsId);
}
Hope it help someone.

Angular 4: Ng2SearchPipeModule using this module for the search. Not working properly on the Data in Numeric

import { Injectable } from '#angular/core';
import { IFavContactSchema } from './favSchema';
#Injectable({
providedIn: 'root'
})
export class FavContactServiceService {
allContactDetails:IFavContactSchema[] = [
{
first_name:"neha",middle_name:"singh",last_name:"sengar",email:"neha.singh931126#gmail.com",mobile_number:9898989898,phone_number:8989898989,notes:"Add to my faver",calling_rate:"frequent"
},
{
first_name:"sonal",last_name:"trivedi",email:"sonal.trivedi#gmail.com",mobile_number:9092312345,phone_number:8989898989,notes:"Add to my onme",calling_rate:"frequent"
},
{
first_name:"oshin",last_name:"sharma",email:"oshin.sharma#gmail.com",mobile_number:9522335434,phone_number:8989898989,notes:"Add to my tow",calling_rate:"frequent"
},
{
first_name:"karasadn",last_name:"sdasd",email:"karan.veer#gmail.com",mobile_number:8839367967,phone_number:8989898989,notes:"Add to my three",calling_rate:"non_frequent"
},
{
first_name:"kunil",last_name:"sharma",email:"kanul.sharma#gmail.com",mobile_number:9097854322,phone_number:8989898989,notes:"Add to my four",calling_rate:"frequent"
},
{
first_name:"kane",last_name:"jain",email:"ranie.jain#gmail.com",mobile_number:8989673422,phone_number:8989898989,notes:"Add to my five",calling_rate:"frequent"
},
{
first_name:"sane",last_name:"sharma",email:"punit.deer#gmail.com",mobile_number:9000000000,phone_number:8989898989,notes:"Add to my six",calling_rate:"non_frequent"
},
];
constructor() { }
addContacts(details:IFavContactSchema){
this.allContactDetails.push(details);
return "Data Added Successfully";
}
getAllContacts(){
return this.allContactDetails;
}
deleteContact(i){
this.allContactDetails.splice(i, 1);
}
getContact(i){
return this.allContactDetails[i];
}
updateContact(i,updatedContact){
this.allContactDetails[i] = updatedContact;
}
}
TS
import { Component, OnInit } from '#angular/core';
import { IFavContactSchema } from '../favSchema';
import { FavContactServiceService } from '../fav-contact-service.service';
#Component({
selector: 'app-favourites-list',
templateUrl: './favourites-list.component.html',
styleUrls: ['./favourites-list.component.css']
})
export class FavouritesListComponent implements OnInit {
key: string = 'first_name'; //set default
reverse: boolean = false;
p: number = 1;
favContactLists:IFavContactSchema[];
constructor(private favConService:FavContactServiceService) { }
ngOnInit() {
this.favContactLists = this.favConService.getAllContacts();
}
deleteContact(i:Number){
this.favConService.deleteContact(i);
}
sort(key){
this.key = key;
this.reverse = !this.reverse;
}
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h2>Fav Contacts</h2>
<nav class="navbar">
<input class="form-control" type="text" name="search" [(ngModel)]="filter">
</nav>
<table class="table">
<thead>
<tr>
<th>#</th>
<th (click)="sort('first_name')">Name
<span class="glyphicon sort-icon" *ngIf="key =='name'" [ngClass]="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
</th>
<th (click)="sort('email')">Email</th>
<th (click)="sort('calling_rate')">Calling Rate</th>
<th (click)="sort('mobile_number')">Mobile Number</th>
<th>Actions</th>
</tr>
</thead>
<tbody *ngIf="favContactLists?.length > 0; else no_record">
<tr *ngFor="let contact of favContactLists| filter:filter | orderBy: key : reverse| paginate: { itemsPerPage: 5, currentPage: p };let i=index">
<td>{{ i+1 }}</td>
<td>{{ contact.first_name + " " }}{{contact.middle_name ? contact.middle_name : ""}}{{ " " + contact.last_name }}</td>
<td>{{ contact.email }}</td>
<td *ngIf="contact.calling_rate == 'frequent'; else non_frequent" >{{ "Frequent" }}</td>
<ng-template #non_frequent><td>{{ "Non Frequent" }}</td></ng-template>
<td >{{ contact.mobile_number }}</td>
<td><a [routerLink]="['/edit', i+1]">
<span class="glyphicon glyphicon-pencil"></span>
</a>
<a (click) = "deleteContact(i)">
<span class="glyphicon glyphicon-trash"></span>
</a>
</td>
</tr>
</tbody>
<ng-template #no_record>
<tbody>
<td colspan="5" class="active cen" align="center">No Record Found</td>
</tbody>
</ng-template>
<pagination-controls (pageChange)="p = $event"></pagination-controls>
</table>
</div>
</body>
</html>
I am new to Angular facing a small issue.
Using the Ng2SearchPipeModule for the search It is working fine for the Data in string but not with the data in Number. I am attaching the Screenshot below...
For some search scenario working fine but for some not.
Please Help.
There are two images one with the normal search and one in which all the records are there even if it doesnot match the filtering criteria

Categories