Array is empty, even though it is set in attached - dart

I have the following code:
Grid get _gridA => $['myGridA'];
Grid get _gridB => $['myGridB'];
Grid get _gridC => $['myGridC'];
List<Grid> _grids = [];
Grid _selectedGrid = null;
attached(){
// Sets array and sets the defaul selected Grid.
_grids = [_gridA, _gridB, _gridC];
_selectedGrid = _grids[0];
}
onTabChange(index, _){
//crashes here, because at this point, _grids is still [] and not [a,b,c]
_selectedGrid = _grids[index];
}
Is there a way to resolve this? set doesnt do anything either.
When trying to instantiate it at the top where i defined it as [], I would get the error that I cant have non-static items in my array.

Related

How do you add an initial selection for Angular Material Table SelectionModel?

The Angular Material documentation gives a nice example for how to add selection to a table (Table Selection docs). They even provide a Stackblitz to try it out.
I found in the code for the SelectionModel constructor that the first argument is whether there can be multiple selections made (true) or not (false). The second argument is an array of initially selected values.
In the demo, they don't have any initially selected values, so the second argument in their constructor (line 36) is an empty array ([]).
I want to change it so that there is an initially selected value, so I changed line 36 to:
selection = new SelectionModel<PeriodicElement>(true, [{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}]);
This changes the checkbox in the header to an indeterminate state (as expected), but does not cause the row in the table to be selected. Am I setting the initial value incorrectly, or what am I missing here? How can I set an initially selected value?
Tricky one. You need to initialize the selection by extracting that particular PeriodicElement object from your dataSource input, and passing it to the constructor.
In this particular case, you could code
selection = new SelectionModel<PeriodicElement>(true, [this.dataSource.data[1]);
It's because of the way SelectionModel checks for active selections.
In your table markup you have
<mat-checkbox ... [checked]="selection.isSelected(row)"></mat-checkbox>
You expect this binding to mark the corresponding row as checked. But the method isSelected(row) won't recognize the object passed in here as being selected, because this is not the object your selection received in its constructor.
"row" points to an object from the actual MatTableDataSource input:
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
But the selection initialization:
selection = new SelectionModel<PeriodicElement>(true, [{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}]);
happens with a new object you create on the fly. Your selection remembers THIS object as a selected one.
When angular evaluates the bindings in the markup, SelectionModel internally checks for object identity. It's going to look for the object that "row" points to in the internal set of selected objects.
Compare to lines 99-101 and 16 from the SelectionModel source code:
isSelected(value: T): boolean {
return this._selection.has(value);
}
and
private _selection = new Set<T>();
I was facing the same issue, I used dataSource to set the initial value manually in ngOnInit()
ngOnInit() {
this.dataSource.data.forEach(row => {
if (row.symbol == "H") this.selection.select(row);
});
}
If you do the following, it works too
selection = new SelectionModel<PeriodicElement>(true, [ELEMENT_DATA[1]])
To select all you can do
selection = new SelectionModel<PeriodicElement>(true, [...ELEMENT_DATA])
I hope the answer is helpful
Or more dynamically if you have a set of values and you want to filter them before:
selection = new SelectionModel<PeriodicElement>(true, [
...this.dataSource.data.filter(row => row.weight >= 4.0026)
]);
This gets more tricky if you have data loading asynchronously from an api. Here is how I did it:
Firstly I have implemented the DataSource from "#angular/cdk/table". I also have an RxJS Subject that fires whenever data is loaded (first time or when user changes page in the pagination section)
export abstract class BaseTableDataSource<T> implements DataSource<T>{
private dataSubject = new BehaviorSubject<T[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
private totalRecordsSubject = new BehaviorSubject<number>(null);
public loading$ = this.loadingSubject.asObservable();
public dataLoaded$ = this.dataSubject.asObservable();
public totalRecords$ = this.totalRecordsSubject.asObservable().pipe(filter(v => v != null));
constructor(){}
connect(collectionViewer: CollectionViewer): Observable<T[]>{
return this.dataSubject.asObservable();
}
disconnect(collectionViewer: CollectionViewer): void {
this.dataSubject.complete();
this.loadingSubject.complete();
this.totalRecordsSubject.complete();
}
abstract fetchData(pageIndex, pageSize, ...params:any[]) : Observable<TableData<T>>;
abstract columnMetadata(): {[colName: string]: ColMetadataDescriptor };
loadData(pageIndex, pageSize, params?:any[]): void{
this.loadingSubject.next(true);
this.fetchData(pageIndex, pageSize, params).pipe(
finalize(() => this.loadingSubject.next(false))
)
.subscribe(data => {
this.totalRecordsSubject.next(data.totalNumberOfRecords);
this.dataSubject.next(data.records)
});
}
}
Now when I want to pre-select a row, I can write a function like this in my component which hosts a table that uses an implementation of the above mentioned data source
selectRow(rowSelectionFn: (key: string) => boolean){
this.dataSource.dataLoaded$.pipe(takeUntil(this.destroyed$))
.subscribe(data => {
const foundRecord = data.filter(rec => rowSelectionFn(rec));
if(foundRecord && foundRecord.length >= 0){
this.selection.toggle(foundRecord[0]);
}
});
}

Knockout JS - observing a mutation in any property of an array without ko.mapping

In my application I have to show only the top 5 items of a long list that have the highest rating. I have implemented this as follows:
The long list is an array that I have turned into an observable array with all elements as observables with ko.mapping, and the top 5 items are a computed array that depends on the long list. Whenever anything in the long list changes the computed array resorts the long list and takes the top 5 items.
My problem is that the long array with ko.mapping takes up 60MB of memory, whereas without ko.mapping it only takes 4MB. Is there a way to achieve this effect without ko.mapping the long array?
Here is a fiddle in which I have recreated the scenario with a smaller and simpler long array, but it's just for you to understand what I'm talking about.
This is the long array, for the demo I've made it 12 elements long:
this.longArray = ko.mapping.fromJS([
{name:"Annabelle"},
{name:"Vertie"},
{name:"Charles"},
{name:"John"},
{name:"AB"},
{name:"AC"},
{name:"AD"},
{name:"AE"},
{name:"AF"},
{name:"AG"},
{name:"AH"},
{name:"AJ"}
]);
And this is the computed array(showing only the top 5):
this.sortedTopItems = ko.computed(function() {
return self.longArray().sort(function(a, b) {
if(a.name() < b.name()) return -1;
if(a.name() > b.name()) return 1;
return 0;
}).slice(0, 5);
}, this);
The change one button is to simulate the long array changing and the reset button is to reset the array to its initial state.
You sure can, but the simplest way would be to filter the data before putting into knockout. If you only ever care about the first 5. Let's assume your long array of items is called data. Note that I'm not able to test this right now, but it should give you a good idea.
const sortedTopItems = ko.observableArray([]);
// Call with new data
const update = (data) => {
data.sort((a,b) => a.name - b.name);
sortedTopItems(data.slice(0, 5));
}
This handles the case for simple data where it's not observable. If you want the actual data items (rows) to be observable then I'd do the following:
const length = 5;
// Create an empty array and initialize as the observable
const startData = new Array(length).map(a => ({}));
const sortedTopItems = ko.observableArray(startData);
// Call with new data
const update = (data) => {
data.sort((a,b) => a.name - b.name);
for(let i = 0; i < length; i++) {
const item = sortedTopItems()[i];
ko.mapping.fromJS(data[i], item); // Updates the viewModel from data
}
}

PHPExcel str_replace

i want to convert my excel hyperlink's path to open links with PHPExcel.
$links = $objPHPExcel->getActiveSheet()->getHyperlinkCollection();
This method will return an array of hyperlink objects, indexed by cell address; and you could then use array_filter() with an appropriate callback and the ARRAY_FILTER_USE_KEY flag set to extract those within a specific range.
my var_dump($links); output :
But i dont know how to loop the array of objects with array_filter() function..
I try :
$test = str_replace($links, "file", "mnt");
var_dump($test);
and i got the error above.. Any ideas please ?
The collection is an array of objects, indexed by cell address; and the PHPExcel_Cell_Hyperlink object has a set of documented methods for accessing and setting its data:
foreach($links as $cellAddress => $link) {
// get the URL from the PHPExcel_Cell_Hyperlink object
$url = $link->getUrl();
// change the URL however you want here
$url = str_replace($url, "file", "mnt");
// Set the new value for the link
$link->setUrl($url);
}
If you want to modify just those URLs for cells in column N, then you can wrap them in an if test:
foreach($links as $cellAddress => $link) {
// Test for column N
sscanf($cellAddress, '%[A-Z]%d', $column, $row);
if ($column == 'N') {
// get the URL from the PHPExcel_Cell_Hyperlink object
$url = $link->getUrl();
// change the URL however you want here
$url = str_replace($url, "file", "mnt");
// Set the new value for the link
$link->setUrl($url);
}
}

jsViews dynamic linking to a different item in array

I am trying to have a dynamic if linking to a property of a different item in an array.
My current code:
Loader
for (...) {
var index = this.App.Data.Questions.push({
...
}) - 1;
if (CompareGuids(this.App.Data.Questions[index].QuestionId, '06EF685A-629C-42A5-9394-ACDEDF4798A5')) {
this.App.PregnancyQuestionId = index;
}
Template
{^{if ~root.Data.Questions[~root.PregnancyQuestionId].Response.ResponseText == "true"}}
{{include #data tmpl="Clinical-History-QuestionWrapper-SingleQuestion"/}}
{{/if}}
It works for the initial loading, but it does not update.
Note I assume I could achieve this with a boolean property in ~root, and then have a $.observable(...).oberserve(...) update this property, but I would prefer to have a direct access.
It looks like all you need to do is make sure that you are changing the PregnancyQuestionId observably. Just assigning a value cannot trigger data-linking to update the UI.
You need to write:
$.observable(this.App).setProperty("PregnancyQuestionId", index);
That should then trigger the binding correctly...

jqTreeView - getting selected node's value in select event

Following is how I populate my jqTreeView.
View
#Html.Trirand().JQTreeView(
new JQTreeView
{
DataUrl = Url.Action("RenderTree"),
Height = Unit.Pixel(500),
Width = Unit.Pixel(150),
HoverOnMouseOver = false,
MultipleSelect = false,
ClientSideEvents = new TreeViewClientSideEvents()
{
Select="spawnTabAction"
}
},
"treeview"
)
<script>
function spawnTabAction(args, event) {
alert(args);
}
</script>
Controller
public JsonResult RenderTree()
{
var tree = new JQTreeView();
List<JQTreeNode> nodes = new List<JQTreeNode>();
nodes.Add(new LeafNode { Text = "Products", Value="Product/Product/Index" });
FolderNode fNode = new FolderNode { Text = "Customers" };
fNode.Nodes.Add(new LeafNode() { Text = "Today's Customers", Value = "Customer/Customer/Today" });
nodes.Add(fNode);
nodes.Add(new LeafNode { Text = "Suppliers", Value = "Supplier/Supplier/Index" });
nodes.Add(new LeafNode { Text = "Employees", Value = "Employee/Employee/Index" });
nodes.Add(new LeafNode { Text = "Orders", Value = "Order/Order/Index" });
return tree.DataBind(nodes);
}
What I want to do is spawn a tab based on the Value of the selected node. I tried a lot but couldn't get hold of the selected node's value.
Later I checked the DOM of rendered page and found that the value is nowhere added to the node but magically when I select the node the value appears in a hidden control by the name treeview_selectedState (treeview being the id of the control). I even traced all ajax calls but couldn't find anything.
Questions:
1) Where does it keep the Values of tree nodes?
2) How do I get the Selected Node's value in select event?
I even tried to get the treeview_selectedState control's value in select event but it returned [].
Then I added a button the view and hooked that onto a js function and found the value there. It makes me think that the value is not available in select event, am I right in thinking that?
I don't think getting selected node's value should be a this big deal? Am I missing something very obvious?
Thanks,
A
After trying so many things , I checked their demo and found the hints there (I shouldve done this as the first thing).
It was actually pretty straight forward
function spawnTabAction(args, event) {
alert($("#treeview").getTreeViewInstance().getNodeOptions(args).value);
}
Thanks,
A

Resources