Dynamically Enable/Disable Mat-Selection-List Mat-List-Option - angular-material

I have the following mat-selection-list. I need it to enable the options in a cascading fashion. i.e. The Second Selection will not be enabled until the First Selection is selected. The Third Selection will not be enabled until the Second Selection is select, etc...
Here is the html code for the list:
<mat-selection-list id='selectedParameters' [(ngModel)]="selectedCriteria">
<mat-list-option *ngFor="let item of incomingParameters" [selected]="item.selected" [value]="item.name"
[disabled]="item.disabled" checkboxPosition="before" (click)="GetChange(item)">
{{item.name}}
</mat-list-option>
</mat-selection-list>
Here is how I populate the List:
if (this.data.criteria.FirstSelection) {
arr.push({
name: 'First Selection',
selected: false,
disabled: 'false',
});
}
if (this.data.criteria.SecondSelection) {
arr.push({
name: 'Second Selection',
selected: false,
disabled: 'true',
});
}
if (this.data.criteria.ThirdSelection) {
arr.push({
name: 'Third Selection',
selected: false,
disabled: 'true',
});
}
if (this.data.criteria.FourthSelection) {
arr.push({
name: 'Fourth Selection',
selected: false,
disabled: 'true',
});
}
if (this.data.criteria.FifthSelection) {
arr.push({
name: 'Fifth Selection',
selected: false,
disabled: 'true',
});
}
if (this.data.criteria.Sixth Selection) {
arr.push({
name: 'Sixth Selection',
selected: false,
disabled: 'true',
});
}
How can I cascade the enabling/disabling of the options?

Nice question, here is my solution, get the length of the selected array and enable those that are less than the value!
html
<h1 class="mat-headline">MatSelectionList</h1>
<h2 class="mat-subheading-1">Input compareWith is not triggered</h2>
<mat-selection-list
#matSelectionList
[compareWith]="compareServiceTypes"
[(ngModel)]="data"
(ngModelChange)="uncheck($event)"
multiple
>
<mat-list-option
checkboxPosition="before"
[value]="s.id"
[selected]="data.includes(s.id)"
*ngFor="let s of serviceTypes; trackBy: s?.id; let i = index"
[disabled]="i > getMax()"
>
{{ s.label }}
</mat-list-option>
</mat-selection-list>
{{ data | json }}
<div class="mat-small material-version">
#angular/material: {{ version.full }}
</div>
ts
import { ViewChild } from '#angular/core';
import { Component } from '#angular/core';
import { MatSelectionList, VERSION } from '#angular/material';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
#ViewChild('matSelectionList') matSelectionList: MatSelectionList;
version: any;
data: any;
serviceTypes = [];
constructor() {
this.version = VERSION;
this.data = [];
setTimeout(() => {
this.serviceTypes = [
{
id: 1,
label: 'Service type 1',
},
{
id: 2,
label: 'Service type 2',
},
{
id: 3,
label: 'Service type 2',
},
{
id: 4,
label: 'Service type 2',
},
{
id: 5,
label: 'Service type 2',
},
];
}, 1000);
}
uncheck(value) {
let found = null;
this.serviceTypes.forEach((item, index) => {
if (
(this.data[index] || this.data[index] === 0) &&
item.id !== this.data[index] &&
!(found || found === 0)
) {
found = index;
}
});
if (found || found === 0) {
this.data.splice(found);
}
}
getMax() {
return this.data.length;
}
compareServiceTypes(st1: any, st2: any) {
console.log('compareServiceTypes');
// const result = st1 && st2 ? st1.id === st2.id : st1 === st2;
return st1 && st2 ? st1.id === st2.id : st1 === st2;
}
}
stackblitz

Related

Using unescaped '#' characters on Ag Grid Enterprise React on Context Menu

When I am using the Ag-Grid context menu on application, I get a message on console saying:
[Deprecation] Using unescaped '#' characters in a data URI body is deprecated and will be removed in M68, around July 2018. Please use '%23' instead. See https://www.chromestatus.com/features/5656049583390720 for more details.
I really don't get any error, but I'm afraid on the message. Can any one update any thing about this message?
This is the component that use this.sate.columnDefs with renderframework like that:
<AgGridReact
// properties
columnDefs={this.state.columnDefs}
rowData={consumers.items}
animateRows
enableColResize
enableSorting={true}
rowSelection="single"
suppressMenuHide={true}
enableFilter={true}
onCellClicked={this.onCellClicked.bind(this)}
onGridReady={this.state.onGridReady}
paginationPageSize={10}
pagination={true}
multiSortKey="ctrl"
getContextMenuItems={this.state.getContextMenuItems}
/>
columnDefs: [
{
headerName: "",
suppressFilter: true,
width: 30,
cellRendererFramework: function (params) {
if (params.data.permissions.length > 0) {
return <i className="fa fa-ellipsis-v" />;
}
}
},
{
headerName: language.LAST_NAME,
field: "person.last_name",
enableRowGroup: true,
filter: "agSetColumnFilter",
},
{
headerName: language.FIRST_NAME,
field: "person.first_name",
enableRowGroup: true,
filter: "agSetColumnFilter",
}
],
sortingOrder: ["desc", "asc", null],
getContextMenuItems: this.getContextMenuItems.bind(this),
onGridReady: function (params) {
var sort = [
{
colId: "person.last_name",
sort: "asc"
},
{
colId: "person.first_name",
sort: "asc"
},
{
colId: "medical_id",
sort: "asc"
},
{
colId: "person.date_of_birth",
sort: "asc"
}
];
this.gridApi = params.api;
this.gridApi.setSortModel(sort);
params.api.sizeColumnsToFit();
}
getContextMenuItems(params) {
let language = languageActions.getLanguage();
const { props } = this;
this.setState({
showActionDiv: false
});
var aResult = [];
params.node.data.permissions.map((permision, index) => {
let language = languageActions.getLanguage();
switch (permision) {
case "Update":
aResult.push(
{
name: language.VIEW_DETAIL,
icon: '<span class="fa fa-edit icon-ag-grid"></span>',
action: () => {
//console.log(this.props);
this.props.toggleShowProfile();
}
}
);
break;
case "Read":
aResult.push(
{
name: language.VIEW_SCHEDULE,
icon: '<span class="fa fa-calendar icon-ag-grid"></span>',
action: () => {
this.props.toggleShowScheduledServices();
}
}
);
break;
}
});
aResult.push(
"separator",
"copy",
"csvExport",
"excelExport",
"autoSizeAll");
return aResult;
}

jquery select2 return json result name

I am new in jquery select2, in result return id, text and name where id is value I know how to get return id(value) with x$("inputBox").val();. but I want get return name in jquery-select2.
Is there any method to get the return name?
x$("#{id:city_combo_box}").select2({
placeholder:"Select City",
allowClear:true,
minimuminputLength:2,
templateResult: formatRepo,
escapeMarkup: function (markup) {return markup},
templateSelection: formatRepoSelection,
multiple:false,
ajax: {
url:ajaxurl,
dataType:"json",
data: function(params){
pp = params.term;
return{
startKey: pp,
page: params.page,
count: 10
};
},
processResults: function (data, params){
var k = data.viewentry;
console.log(k);
params.page = params.page;
return {
results: $.map(k, function(obj) {
return {id: (obj.entrydata[1].text[0]), text: obj.entrydata, name: (obj.entrydata[0].text[0])};
})
};
}
}
}).on("change", function(e){ x$("#{id:claim_limit_text}").val(x$("#{id:city_combo_box}").val(id));
}).trigger("change");
})
The only solution I came across is this:
html
<div id="ddWrapper1">
<select id="dd1"></select>
</div>
js
$(document).ready(function() {
var ddDate = [{
id: 1,
text: 'some item'
}, {
id: 2,
text: 'even more items'
}, {
id: 3,
text: 'oh no'
}, {
id: 4,
text: 'that is a realy long item name...'
}];
$('#dd1').select2({
data: ddDate,
allowClear: true,
multiple: true,
placeholder: '[dd1] select some items'
});
$('#dd1').on('change', function() {
console.log($('#dd1').data('select2').$selection[0].innerText);
})
});
But I have to admit that the result is not the nicest.

Kendo grid footer template sum issue

var dataSourceDashboard = new kendo.data.DataSource({
pageSize: 20,
type: "json",
transport: {
read: function (operation) {
if (navigator.onLine) {
$.ajax({
url: '/Home/Dashboard_Read/',
type: "GET",
dataType: "json",
success: function (response) {
try
{
localStorage.setItem("Dashboard_Read", JSON.stringify(response));
}
catch (domException)
{
if (domException.name === 'QuotaExceededError' ||
domException.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
// Fallback code comes here.
$("#progressMsgError").html("Cannot save the data for offline use, please clear the cache, or call administrator!");
$('#myModalError').modal('show');
}
}
operation.success(response);
BindSitesCombo(response);
//// initial sync of data
//var cashedDataBaseJson = [];
//var cashedDataBase = localStorage.getItem("cashedDataBase");
//if (cashedDataBase != null || cashedDataBase != undefined) {
// cashedDataBaseJson = JSON.parse(cashedDataBase);
// if (cashedDataBaseJson.length > 0) {
// syncInitialData(cashedDataBaseJson);
// localStorage.setItem("cashedDataBase", JSON.stringify(cashedDataBaseJson));
// }
//}
//else
//{
// syncInitialData(response);
// localStorage.setItem("cashedDataBase", JSON.stringify(response));
//}
var cashedDataBase = localStorage.getItem("cashedDataBase");
if (cashedDataBase == null || cashedDataBase == undefined) {
localStorage.setItem("cashedDataBase", JSON.stringify(response));
}
else {
var cashedDataBaseJson = [];
var cashedDataBase = localStorage.getItem("cashedDataBase");
if (cashedDataBase != null || cashedDataBase != undefined) {
cashedDataBaseJson = JSON.parse(cashedDataBase);
var i = response.length;
while (i--)
{
var ifsiteisinthelist = contains(cashedDataBaseJson, response[i]);
if (ifsiteisinthelist == false)
{
cashedDataBaseJson.push(response[i]);
}
}
localStorage.setItem("cashedDataBase", JSON.stringify(cashedDataBaseJson));
}
}
rempvesyncedlinks();
},
error: function (response)
{
window.location.href = "/account/login";
}
});
}
else {
var cashedData = localStorage.getItem("Dashboard_Read");
if (cashedData != null || cashedData != undefined) {
//if local data exists load from it
var data = JSON.parse(cashedData);
operation.success(data);
BindSitesCombo(data);
rempvesyncedlinks();
}
}
}
},
schema: {
model: {
id: "SiteID",
}
},
//change: function (e) {
// $.each(dataSourceDashboard.data(), function (index, value) {
// $('#cmbAllSites')
// .append($("<option></option>")
// .attr("value", value.SiteID)
// .text(value.SiteName));
// });
//}
change: function (e) {
rempvesyncedlinks();
},
aggregate: [
{ field: "DailyTotalFormated", aggregate: "sum" },
{ field: "WeeklyTotalFormated", aggregate: "sum" },
{ field: "WeeklySiteTotalFormated", aggregate: "sum" },
{ field: "WeeklyGoal", aggregate: "sum" }
],
});
$(function () {
$("#gridDashboard").kendoGrid({
dataSource: dataSourceDashboard,
filterable: false,
groupable: false,
toolbar: false,
pageable: {
change: function (e) {
rempvesyncedlinks();
}
},
sortable: true,
height: 600,
columns: [
{ field: "SiteName", title: "MY COMPANIES", template: '#=SiteName#',footerTemplate: "Total " },
{ field: "DailyTotalFormated", title: "MY DAILY TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklyTotalFormated", title: "MY WEEKLY TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklySiteTotalFormated", title: "WEEKLY SITE TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklyGoal", title: "WEEKLY SITE GOAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "", title: "SYNC", template: "# if (isSynced == true) { #" +
"<div style='width: 130px;margin: auto;'><img src='/images/ready.png' alt='Up-to-date' /><div style='font-size:15px; font-weight:bolder; float: right;'>Ready</div></div>" +
"# } else { #" +
"<div style='width: 130px;margin: auto;'><img src='/images/pleasesync.png' alt='Up-to-date' /><div style='font-size:15px; font-weight:bolder; float: right;'>Please Sync</div></div>" +
"# } # <a id='syncforoffline#=SiteID#' href='##' onclick='syncDataForSite(#=SiteID#);return false;'>Sync for offline</a>"
},
{ field: "SiteLogo", title: " ", hidden : true },
],
editable: false
});
$("#cmbAllSites").change(function ()
{
var di = dataSourceDashboard.data()[this.selectedIndex - 1];
setSiteID(di.SiteID, di.SiteLogo, di.SiteName);
});
});
Footer sum is not calculated
What is wrong in this code, why does the total show last row by default?
I fixed the issue. I am just adding:
model: {
id: "SiteID",
fields: {
SiteName: { type: "string" },
DailyTotalFormated: { type: "number" },
WeeklyTotalFormated: { type: "number" },
WeeklySiteTotalFormated: { type: "number" },
WeeklyGoal: { type: "number" }
}
}

ng2-highcharts chart update after load

I'm using angular 2, firebase and ng2-highcharts.
I assign data after I receive them from firebase like so :
this.items = af.database.list('/items');
this.optionsAsync = this.items.map(data => {
this.options.series[0].data = data.map(item => ([item.x, item.y]));
return this.options;
});
Then in my view template I have :
<div [ng2-highcharts]="optionsAsync | async"></div>
This is working fine at first load. But unfortunately when new data are received chart is not updated. Any idea ?
I found a solution by referencing highcharts component with #ViewChild like so :
in component class :
import { ViewChild, Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
directives: [Ng2Highcharts]
})
export class AppComponent {
#ViewChild(Ng2Highcharts)
chartElement: Ng2Highcharts;
private chartData = {
chart: {
zoomType: 'x'
},
colors: ['rgba(255,0,255,1)'],
title: {
text: 'Items'
},
credits: '',
series: [{
type: 'area',
name: 'Items',
data: []
}]
};
chartData$ = new Subject();
ngOnInit() {
this.items.subscribe((data: any) => {
this.chartData.series[0].data = data.map(item => ([item.x, parseFloat(item.y)]) );
this.chartData$.next(this.chartData);
if(this.chartElement && this.chartElement.chart) {
var serieRef = this.chartElement.chart.series[0];
serieRef.setData(this.chartData.series[0].data);
}
});
}
}

Angular UI Grid not updating directives in cells

I have a ui grid that contains a directive, this directive has an isolated scope and changes it's template basing on some logic.
The problem is that, when sorting (and also when PAGING), the 'logic' of the directive seems to not be correctly "re-evaluated".
In the specific example, the rightmost column should only see some "11" while if you try to sort by id (or the other fields) you'll see some spurios '0' appearing.
this is the ui:
<div ng-app="myapp">
<div ng-controller="myctrl">
<div ui-grid="gridOptions" ng-style="gridStyle"></div>
</div>
</div>
this is the js:
var myapp = angular.module('myapp', ["ngRoute", "ui.grid"])
.controller('myctrl', function($scope) {
$scope.gridOptions = {
data: [{
id: 1,
name: "Max",
other: "pippo",
number: 1
}, {
id: 2,
name: "Adam",
other: "pluto",
number: 0
}, {
id: 3,
name: "Betty",
other: "paperino",
number: 0
}, {
id: 4,
name: "Sara",
other: "fava",
number: 1
}, {
id: 5,
name: "Favonio",
other: "favona",
number: 1
}],
columnDefs: [{
field: "id",
displayName: "ID"
}, {
field: "name",
displayName: "Name"
}, {
field: "other",
displayName: "Other"
}, {
field: "number",
cellTemplate: '<div class="ui-grid-cell-contents"><mydir data="row.entity"></mydir></div>'
}]
};
}).directive("mydir", function() {
return {
restrict: 'E',
scope: {
data: "=",
},
template: '<div><label ng-if="data.number==1">{{set}}</label></div>',
link: function(scope, iElement, iAttrs) {
scope.set = -1;
if (scope.data.number == 0) {
scope.set = 00;
} else {
scope.set = 11;
}
}
}
});
and here's a fiddle:
https://jsfiddle.net/27yrut4n/
Any hint?
In the end it's a known bug:
https://github.com/angular-ui/ui-grid/issues/4869
And I solved using watch like it's said here:
Directive rendered via UI-Grid cellTemplate rendering incorrectly

Resources