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

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]);
}
});
}

Related

MVC drop down list is not picking up selected item?

My model contains an array of zip code items (IEnumerable<SelectListItem>).
It also contains an array of selected zip codes (string[]).
In my HTML page, I want to render each selected zip code as a drop down with all the zip code options. My first attempt did not work:
#foreach (var zip in Model.ZipCodes) {
Html.DropDownList( "ZipCodes", Model.ZipCodeOptions )
}
I realized that although that would produce drop downs with the right "name" attribute, it wouldn't know which element of ZipCodes holds the value for that particular box, and might just default to the first one.
My second attempt is what really surprised me. I explicitly set the proper SelectListItem's Selected property to true, and it still rendered a control with nothing selected:
#foreach (var zip in Model.ZipCodes) {
Html.DropDownList( "ZipCodes", Model.ZipCodeOptions.Select( x => (x.Value == zip) ? new SelectListItem() { Value = x.Value, Text = x.Text, Selected = true } : x ) )
}
There, it's returning a new IEnumerable<SelectListitem> that contains all the original items, unless it's the selected item, in which case that element is a new SelectListItem with it's Selected property set to true. That property is not honored at all in the final output.
My last attempt was to try to use an explicit index on the string element I wanted to use as the value:
#{int zipCodeIndex = 0;}
#foreach (var zip in Model.ZipCodes) {
Html.DropDownList( "ZipCodes[" + (zipCodeIndex++) + "]", Model.ZipCodeOptions )
}
That doesn't work either, and probably because the name is no longer "ZipCodes", but "ZipCodes[x]". I also received some kind of read-only-collection error at first and had to change the type of the ZipCodes property from string[] to List<string>.
In a forth attempt, I tried the following:
#for (int zipCodeIndex = 0; zipCodeIndex < Model.ZipCodes.Count; zipCodeIndex++)
{
var zip = Model.ZipCodes[zipCodeIndex];
Html.DropDownListFor( x => x.ZipCodes[zipCodeIndex], Model.ZipCodeOptions )
}
That produces controls with id like "ZipCodes_1_" and names like "ZipCodes[1]", but does not select the right values. If I explicitly set the Selected property of the right item, then this works:
#for (int zipCodeIndex = 0; zipCodeIndex < Model.ZipCodes.Count; zipCodeIndex++)
{
var zip = Model.ZipCodes[zipCodeIndex];
Html.DropDownListFor( x => x.ZipCodes[zipCodeIndex], Model.ZipCodeOptions.Select( x => (x.Value == zip) ? new SelectListItem() { Value = x.Value, Text = x.Text, Selected = true } : x ) )
}
However, the problem with that approach is that if I add a new drop downs in JavaScript and give them all the name "ZipCodes", then those completely override all the explicitly indexed ones, which never make it to the server. It doesn't seem to like mixing the plain "ZipCodes" name with explicit array elements "ZipCodes[1]", even though they map to the same variable when either is used exclusively.
In the U.I., user's can click a button to add a new drop down and pick another zip code. They're all named ZipCodes, so they all get posted to the ZipCodes array. When rendering the fields in the loop above, I expect it to read the value of the property at the given index, but that doesn't work. I've even tried remapping the SelectListItems so that the proper option's "Selected" property is true, but it still renders the control with nothing selected. What is going wrong?
The reason you first 2 snippets do not work is that ZipCodes is a property in your model, and its the value of your property which determines what is selected (not setting the selected value in the SelectList constructor which is ignored). Since the value of ZipCodes is an array of values, not a single value that matches one of the option values, a match is not found and therefore the first option is selected (because something has to be). Note that internally, the helper method generates a new IEnumerable<SelectListItem> based on the one you provided, and sets the selected attribute based on the model value.
The reason you 3rd and 4th snippets do not work, is due to a known limitation of using the DropDownListFor() method, and to make it work, you need to use an EditorTemplate and pass the SelectList to the template using AdditionalViewData, or construct a new SelectList in each iteration of the loop (as per your last attempt). Note that all it needs to be is
for(int i = 0; i < Model.ZipCodes.Length; i++)
{
#Html.DropDownListFor(m => m.ZipCodes[i],
new SelectList(Model.ZipCodeOptions, "Value", "Text", Model.ZipCodes[i]))
}
If you want to use just a common name (without indexers) for each <select> element using the DropDownList() method, then it needs to be a name which does not match a model property, for example
foreach(var item in Model.ZipCodes)
{
#Html.DropDownList("SelectedZipCodes",
new SelectList(Model.ZipCodeOptions, "Value", "Text", item))
}
and then add an additional parameter string[] SelectedZipCodes in you POST method to bind the values.
Alternatively, use the for loop and DropDownListFor() method as above, but include a hidden input for the indexer which allows non-zero based, non consecutive collection items to be submitted to the controller and modify you script to add new items using the technique shown in this answer
Note an example of using the EditorTemplate with AdditionalViewData is shown in this answer

DropDownList in my edit view mvc

i have List view and in every rows it has the "Actualizar" link action and that one takes me to the edit view in which i have some dropdownLists available for updating my existing data but my big problem is that i want the dropdownlist to first load the data is save. how can i set the dropdownlist to load the data of the model a return and let me choose other options
controller:
public ActionResult ActualizarDispositivo(int id )
{
dropDown();
var equipo= _db.equipo.Include(m=>m.marca).Include(mo=>mo.modelo.Single(b => b.idEquipo==id);
ViewBag.idMarca = _db.marca.ToList().Select(Mar => new SelectListItem
{
Value = Mar.idMarca.ToString(),
Text = Mar.Descripcion.ToString(),
Selected = true
});
return View("ActualizarDispositivo",equipo);
}
in the edit view i have this
#Html.DropDownListFor(m=>m.idMarca,(IEnumerable<SelectListItem>)ViewBag.idMarca)
The code you are using should work, if you simply remove the Selected = true. Currently you are setting all of the DropDownList's values to selected.
I'm not sure which performs better, but I do find it more readable to create a select list using:
ViewBag.idMarca = new SelectList(_db.marca.ToList(), "idMarca", "Descripcion");
And then, there may be no need to cast. (Unsure, I avoid the use of ViewBag)
#Html.DropDownListFor(m=>m.idMarca, ViewBag.idMarca)

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...

MVC 3 WebGrid with a dynamic source

I have a dynamic list of data with a dynamic number of columns being created by a PIVOT function. Everything more or less works, but I wanted to apply some custom formatting to some of the columns. I figured out how to get a list of the columns by just taking the first row and casting it like so:
var columns = Model.Comparisons.Select(x => x).FirstOrDefault() as IDictionary<string, object>;
Next I decided to create my List by looping over the "columns", which works as long as I reference the dynamic fields in the "format:" clause by their dynamic field name directly for example:
foreach (var c in columns)
{
switch (c.Key)
{
case "Cost":
cols.Add(grid.Column(
columnName: c.Key,
header: c.Key,
format: (item) => Convert.ToDecimal(item.Cost).ToString("C")));
break;
default:
cols.Add(grid.Column(columnName: c.Key, header: c.Key, format: item => item[c.Key]));
break;
}
}
The "default" does not dynamically get the value of each record. I believe it has to do with the "item[c.Key]" vs item.Cost. The problem is I don't want to have to write different case for each field, primarily because I don't know them ahead of time as the data can change. There are about 6 fields that will always be present. I do know however the datatype, which is why I wanted to put a custom format on them.
EDIT
I managed to solve this by writing an extension method.
public static class DynamicDataHelper
{
public static WebGridColumn GetColumn(this HtmlHelper helper, string vendor)
{
return new WebGridColumn()
{
ColumnName = vendor,
Header = vendor,
Format = (item) => helper.ActionLink(
(string)Convert.ToDecimal(item[vendor]).ToString("C"),
"VendorSearch",
"Compare",
new { Vendor = vendor, mpn = item.MPN },
new { target = "_blank" })
};
}
}
I edited my post with the Html Helper that I wrote that will in effect build the custom WebGridColumn objects I was having problems with. The "vendor" is passed in from the View and is then resolved at runtime. It works great.

Entity Framework - Select specific columns and return strongly typed without losing cast

I'm trying to do something similar to this post where I don't pull back all columns from a particular entity, however my framework makes use of inheritence and I lose scope of the entity type after it's been cast to an anonymous type.
The structure of my Entity Framework has a base entity called Action. From here I've created two inherited entities called Event and Activity. I want to pull back the last X Actions and pass them to my strongly typed view which accepts an Action and from there determines if its an Activity or Event and renders the correct partial view.
if(Model.GetType() == typeof(Event))
{
//render Event view
}
else if(Model.GetType() == typeof(Activity))
{
//render Activity view
}
I can pull the last 10 as an anonymous type and then cast:
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
select new { a.CreatedOn, a.Summary };
List<Action> list = result.AsEnumerable()
.Select(o => new Action {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}).ToList();
However, once I pass the new List of Actions to my strongly typed view it loses scope of whether it's an Activity or an Event since it's been cast as an Action. My question is, without exposing the discriminator column, is there any way to cast each item to the proper type or am I going about this the wrong way?
A bit kludgy, but will work:
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
let IsEvent = a as Event != null
select new { a.CreatedOn, IsEvent, a.Summary };
List<Action> list = result.AsEnumerable()
.Select(o => o.IsEvent ?
(Action) new Event {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}
: (Action) new Activity {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}
}).ToList();
Example with type-specific columns, presuming that e.EventSpecific is of a nullable type.
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
let ev = a as Event
let IsEvent = ev != null
select new { a.CreatedOn, IsEvent, a.Summary, ev.EventSpecific };
List<Action> list = result.AsEnumerable()
.Select(o => o.IsEvent ?
(Action) new Event {
CreatedOn = o.CreatedOn,
Summary = o.Summary,
EventSpecific = o.EventSpecific
}
: (Action) new Activity {
CreatedOn = o.CreatedOn,
Summary = o.Summary,
EventSpecific = o.EventSpecific // will be null, but using o.EventSpecific saves casting
}
}).ToList();
If o.EventSpecific is of a non-nullable type, then you must convert it to a nullable type in the L2E query.
You are probably on the wrong way. At first I would assume that Action should be an abstract class and you should not be able to create instances of it at all. If you then only fetch a subset of the properties and the subset does no longer allow to discriminate between events and activities, it is probably the wrong way to try making events and activities out of them.
So it actually seems not to be a technical problem - it should be quite easy to include some discrimination information in the anonymous type - but a design problem. I suggest to rethink if it is required to discriminate the query result and if so if it is really a good idea to discriminate the result in absence of an discriminator.

Resources