Get data id in array object vuejs - arrays

how to display value data based on index array. here I make a modal edit data, I have a json like the following
[
{
"ID": 3,
"idusers": 3,
"skills": "Go",
"profiency": "Expert",
},
{
"ID": 48,
"skills": "laravel",
"profiency": "laravel",
},
{
"ID": 47,
"skills": "Vue",
"profiency": "Expert",
}
]
table data that I display
<tr v-for="(skill, index) in getSkills" :key="skill.ID">
<td>{{ index + 1 }}</td>
<td>{{ skill.skills }}</td>
<td>{{ skill.profiency }}</td>
<td class="text-xs-center">
<td><div v-if="editBtn == true">
<v-btn class="mr-3" x-small fab v-on:click="handleEdit(item,index)" color="primary"><v-icon>mdi-cancel</v-icon></v-btn>
</td>
</tr>
and this my modal edit
<v-dialog v-model="skillForm" width="500">
<v-container>
<v-text-field outlined dense>
{{profiency}}
</v-text-field>
</v-container>
</v-dialog>
my method
export default {
name: "Skills",
data: function() {
return {
formAddSkills: "",
skillForm: false,
editBtn: "",
skills: {
skills: "",
profiency: "",
},
};
},
computed: {
...mapState({ getSkills: (state) => state.resume.Skills }),
dataSkills() {
return this.skills;
},
},
methods: {
handleEdit(item, index) {
this.skillForm = true;
this.editBtn = true;
this.profiency = item.profiency
// console.log(item)
console.log(index)
},
}
}
the question is how to display data based on ID, when I click the edit button it appears and enters the text field form

Pass skill from your method as a parameter
#click="handleEdit(skill,index)
Then declare a variable, currentObject, and then equate it this.currentObject = skill inside the method.
Then you can access currentObject.id via the v-model binded to your text field.

Related

angular: Translate elements of an object array in a template with ngx-translate

I have been searching for hours how I can translate the values of an object array with the module ngx-translate,
Here is an extract of my code but I don’t know how to implement the json file
Template HTML :
<div class="sort-header-container">
<table matSort class="mat-sort">
<tr *ngFor="let item of items" class="row">
<td class="row">{{item.critere}}</td>
<td>{{item.res}}</td>
</tr>
</table>
</div>
The object array in the service :
items: any[] = [
{ critere: "Code-modèle", res: "Mizuno Shadow 4" },
{ critere: "Code Libellé", res: "KR32" },
{ critere: "Stock", res: 10 },
{ critere: "Prix TTC", res: "Bleu" },
{ critere: "Couleur", res: 42 },
{ critere: "Matière", res: 125 },
{ critere: "Zone", res: 100 },
];
I need to translate only the critere column
Thank you
You need to use the TranslatePipe from ngx-translate.
<div class="sort-header-container">
<table matSort class="mat-sort">
<tr *ngFor="let item of items" class="row">
<td class="row">{{item.critere | translate}}</td>
<td>{{item.res}}</td>
</tr>
</table>
</div>
Make sure your critere field have the corresponding translations in the json translation files
example for en english translation:
{
"Prix TTC": "Price",
"Couleur": "Color",
}
As taken from the example in ngx-translate github
You can use the translate pipe in your code, like this:
<td class="row">{{ item.critere | translate }}</td>
For this to work, your critere would need to be keys in your language file, for example:
{
'Stock': 'Stock english translation',
'Couleur': 'Is this color?'
}
Thank you very much for your answers
Finally here's what I did :
<tr *ngFor="let item_translate of ('PRODUCT.PRODUCT' | translate); let i = index " class="row"
[ngStyle]="item_translate.critere == 'Stock' && stock<0 ?{color:'red'}:{color:'#474646'}">
<td class="row">{{item_translate.critere}}</td>
<td>{{items[i].res}}</td>
</tr>
In my json example fr :
"PRODUCT": {
"PRODUCT": [
{
"critere": "Code-modèle"
},
{
"critere": "Code Libellé"
},
{
"critere": "Stock"
},
{
"critere": "Prix TTC"
},
{
"critere": "Couleur"
},
{
"critere": "Matière"
},
{
"critere": "Zone"
}
]
}

p-dropdown in p-table dynamic rows PrimeNG - version 9 - Stackblitz added

My requirement is to have dropdowns in each row of two columns of grid as below:
Here is stackblitz for my problem: https://stackblitz.com/edit/angular9-primeng9
User can select values for each row and save. I am able to fetch data from data source using service and initialize dropdown options in subscribe of observable. However, I am not able to set the selected item of each row on page load to display pre-existing rows (I think problem of setting up [(ngModel)]).
Also, I need to add a plus button which would add a new row to this table and result should be saved to database on save action. Any guidance / lead to address this issue would be of great help.
Below is HTML code I am using:
<p-table [columns]="cols" [value]="rows">
<ng-template pTemplate="header" let-columns>
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-columns="columns">
<tr>
<td>
<p-dropdown [options]="DropdownSource" [(ngModel)]="rowData.AAttribute" placeholder="Select"
[showClear]="true"></p-dropdown>
</td>
<td>
<p-dropdown [options]="DropdownSource" [(ngModel)]="rowData.BAttribute" placeholder="Select"
[showClear]="true"></p-dropdown>
</td>
</tr>
</ng-template>
</p-table>
and in component (subscribe in onchanges):
this.cols = [
{ "field": "field_0", "header": "A Attribute" },
{ "field": "field_1", "header": "B Attribute" }
];
this.rows = [{ "AAttribute": "Data3", "BAttribute": "DataC" },
{ "AAttribute": "Data5", "BAttribute": "DataE" }];
this.DropdownSource= [
{ "AAttribute": "Data1", "BAttribute": "DataA" },
{ "AAttribute": "Data2", "BAttribute": "DataB" },
{ "AAttribute": "Data3", "BAttribute": "DataC" },
{ "AAttribute": "Data4", "BAttribute": "DataD" },
{ "AAttribute": "Data5", "BAttribute": "DataE" },
{ "AAttribute": "Data6", "BAttribute": "DataF" }]
ngmodel expects object from the array.
refer below stackblitz https://stackblitz.com/edit/angular9-primeng9-dgxsjj
this.mappingRows = [{ "targetCol": "DataF", "SourceCol": this.sourceAttributes.find(p=>p.label === "Data3") },
{ "targetCol": this.targetAttributes[3], "SourceCol": "Data6" },
{ "targetCol": "DataC", "SourceCol": "Data1" }];

sorting not working properly angular 4

I have various tables and I'm trying to sort table using https://www.npmjs.com/package/ngx-order-pipe. I followed their documentation and everything works fine except it is not sorting correctly the columns (here in the example, 'Rank' column)
For example I have a response like this:
"collection": [
{
"name": "John",
"age" : "25",
"details": [
{
"final_rank": "150"
}
]
}
{
"name": "Mark",
"age" : "19",
"details": [
{
"final_rank": "254"
}
]
}
Here's my HTML:
<table>
<thead>
<tr>
<th (click)="setOrder('name')">Name</th>
<th (click)="setOrder('age')">Age</th>
<th (click)="setOrder('final_rank')">Rank</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let Data of collection | orderBy: order:reverse:'case-insensitive'">
<td class="text-truncate">{{Data.name}}</td>
<td class="text-truncate">{{Data.age}}</td>
<td class="text-truncate" *ngIf="!isArray(Data.details)">
<tr> {{Data.details.final_rank}} </tr>
</td>
<td class="text-truncate" *ngIf="isArray(Data.details)"><tr *ngFor="let rankData of Data.details"> {{rankData.final_rank}} </tr></td>
</tr>
</tbody>
</table>
component.ts
order;
reverse = false;
isArray(obj: any) {
return Array.isArray(obj)
}
getData() {
this.http.get('**')
.subscribe(data => {
console.log(data);
});
}
setOrder(value) {
if (this.order === value) {
this.reverse = !this.reverse;
}
this.order = value;
console.log(this.order);
}
Your problem seems to be that you try to sort by a field that is inside of an array of the actual object. I suspect that your library doesn't know how to do the sorting (and that probably rightly so). So what you should do is to transform your data in a format, where it can be sorted.
At some point in your application you have the data:
const originalData = [{
'name': 'John',
'age': '25',
'details': [
{
'final_rank': '150'
}
]
},
{
'name': 'Mark',
'age': '19',
'details': [
{
'final_rank': '254'
}
]
}];
Whata you want to do now is to take that data and to convert it to something else. In this example I want to get the max final_rank value of any of the details items. That max value will be used for sorting. You might want to use another way of defining what value to use, but for this example the max value should do fine.
We can use a map function to transform each value of your original data:
const mappedData = originalData.map(item => ({
// This will do a shallow copy of all the fields of the original object
...item,
// With reduce we can easily find the max ```final_rank``` value
maxRank: item.details.reduce(
// +current.final_rank converts the string to a number
(max, current) => +current.final_rank > max ? current.final_rank : max,
0
)
}));
This should yield a new array which should look the same as your original data, except for an additional maxRank field on the root object.
The resulting object would look something like this:
const mappedData = [{
'name': 'John',
'age': '25',
'maxRank': 150,
'details': [
{
'final_rank': '150'
}
]
},
{
'name': 'Mark',
'age': '19',
'maxRank': 254,
'details': [
{
'final_rank': '254'
}
]
}];
Now you should be able to do sorting based on the maxRank field.

retrieve JSON list with absent Object and replace them by null using Angular2

Here is my JSON array :
"user" : {
"id": 456,
"nickname": "xxx",
"pf": {
"id": 123,
"account": [
{
"accountid": 1494235749,
"status": "New",
"accountnbr": 12345,
"cyc": {
"cycid": 1494404053,
"active": true,
"status": "New",
"name": "QST192017",
},
},
{
"accountid": 1494403399,
"status": "New",
"accountnbr": 915177,
"cyc": {
"cycleid": 1494406299,
"active": true,
"status": "Closed",
"name": "QSL342014"
}
},
{
"accountid": 1494500399,
"status": "New",
"accountnbr": 90010,
}
]
},
}
And this is what I have in my template :
<tr *ngFor="let account of accounts">
<td>{{ account.accountnbr }}</td>
<td>{{ account.cyc.name}}</td>
</tr>
I tried to retrieve a list of all my accounts , and as you can see one of the account has no cyc, and shows an error , any idea how to replace absent JSON object by null in the list ?
PS : I'm using angular2
Thank you.
/K
use account.cyc?.name will solve your problem. when account doesn't have cyc, your template will just show blank without any error.
see documentation of safe-navigation-operator(?).
<tr *ngFor="let account of accounts">
<td>{{ account.accountnbr }}</td>
<td>{{ account.cyc?.name}}</td>
</tr>
This is as simple as using an *ngIf:
<div *ngFor="let acc of account">
<div *ngIf="!acc.cyc">NO CYC ON THIS ACCOUNT</div>
</div>
For this purpose an absent object is null/undefined.
You could also map over the object in your component and set it as null:
account.map(x =>{
if(!x.cyc){
x.cyc = null;
}
return x;
});

how to get particular customers order

/*factory method for getting particular customers order*/
factory.getCustomer = function(customerId) {
for(var i=0,len=customers.length ; i<len ; i++) {
if(customers[i].id === parseInt(customerId)){
return customer[i];
}
}
return {};
};
return factory();
/*Controller*/
myApp.controller('OrdersController',['$scope','$routeParams','customersFactory', function($scope,$routeParams,customersFactory) {
var customerId = $routeParams.customerId;
$scope.customer = null;
function init() {
$scope.customer = customersFactory.getCustomer(customerId);
}
init();
}]);
/*View*/
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>{{customer.name}}'s Orders</h2>
<table class="table table-hover">
<tr>
<th>Product</th>
<th>Total</th>
</tr>
<tr ng-repeat="order in customer.orders">
<td>{{ order.product }}</td>
<td>{{ order.total | currency }}</td>
</tr>
</table>
</div>
</div>
</div>
/*JSON FILE*/
{
"id": "1",
"joined": "2000-12-2",
"name": "Wali",
"city": "Dubai",
"orderTotal": "9.0765",
"orders": [
{
"id": "1",
"product": "protein",
"total": "11.987"
}
]
},
{
"id": "2",
"joined": "2004-12-2",
"name": "Ali",
"city": "London",
"orderTotal": "20.0765",
"orders": [
{
"id": "2",
"product": "bcca",
"total": "2.3456"
},
{
"id": "3",
"product": "baseball",
"total": "4.3456"
}
]
},
{
"id": "3",
"joined": "1980-11-2",
"name": "Zen",
"city": "Australia",
"orderTotal": "6.500",
"orders": [
{
"id": "3",
"product": "chocolate",
"total": "6.4567"
}
]
}
I have made a customers table from which we can perform the CRUD functionality, but when I click to check the particular customer order it is redirecting me to the right view via routing but particular customers orders are not displaying.
can any one suggest a solution for this?
According to your JSON data, the ID is a String, but you are parsing it into an integer, and using ===, which will match only if the value and the type of the compared variables match.
You need to change the if statement, one option is:
if (parseInt(customers[i].id) === parseInt(customerId))
Another option will be:
if (customers[i].id == customerId)
And yet another option is using angular's $filter service.
You need to inject it into your factory, and than in order to get the client, you can use:
var customer = $filter('filter')(customers, {id: customerId.toString()}, true);
return customer.length === 1 ? customer[0] : null;
The toString part is only because your JSON data have ID as as string, and the third argument is set to true to prevent 'like' filter (default $filter behavior will return id 10 for example also if the customerId is 1).

Resources