[Table] Add example with dynamic data (add/remove/edit rows)
Bug, feature request, or proposal:
cdk table API docs need instructions and/or an example of updating the dataSource in the table connecting the table to a data source
What is the expected behavior?
seeing implementation instructions and/or an example of how to send the updated dataSource to the table so that the connect function is called
What is the current behavior?
The docs only cover rendering data on initial load of the component, but if a service updates the data, there isn't a documented way to update the data-table
What are the steps to reproduce?
Providing a Plunker (or similar) is the best way to get the team to see your issue. Plunker template: https://goo.gl/DlHd6U
What is the use-case or motivation for changing an existing behavior?
the md-table API doc hints at an approach but also lacks clarity
Which versions of Angular, Material, OS, TypeScript, browsers are affected?
angular 4 material 2 typescript 2.4 windows
Is there anything else we should know?
Sounds good to me, I'll make an example that includes adding/removing/editing rows.
I hope I can add to this request without creating a new Issue, I've been looking at the example code provided in both the angular material docs and the cdk guide and I'm struggling to understand how to just send my data (a simple array of objects) to the table. Do I need my data to be a BehaviorSubject ? Do I need the typescript get too ?
The example generates data with loops and is quite confusing to me.
A simpler example with just a small simple array would really help ! I'll create a new Issue if needed.
hello @andrewseguin It would be nice if you add collapsible row too.
Hi @andrewseguin, alos would be nice to have example with server data, to get server data is OK, but how to triger on new http.get request on paging, sorting and filtering? (i'm stuck with that).
@Lakston IMO your request deserves a separate issue. While the ExampleDatabase is great as a supplier of 100 rows of random data, it convolutes the Basic Example, and I think the docs could benefit from an even simpler example with maybe a single emission of a hardcoded array of data with Observable.of.
@ilmars luckily an example with an HTTP request just got merged yesterday and will be available on the docs site soon https://github.com/angular/material2/pull/5766
@Lakston what I did to accomplish that was to setup a service to provide the data array to the ExampleDatabase and then looped over each item in the array and fed them into the addUser method from the example, after changing it to match my object. So you can just replace what is being iterated over in the for loop from the example by creating a service to call for that data
for anyone interested in an unpublished example:
https://github.com/angular/material2/pull/5093/files
https://github.com/angular/material2/tree/master/src/demo-app/table
Some help on this would be greatly appreciated :)
https://stackoverflow.com/questions/45382599/angular-2-table-invoke-connect-function
Agreed. I wept for joy when this component arrived. But after about six hours of fiddling with this thing, I still can't get it to work with a meaningful, real-world example. I expected to just point it at an array, and I'd be off and running. But having to create a datasource and a database is especially cumbersome. If the grid is supposed to be truly unopinionated, imo it shouldn't be coupled to observables. I should be able to just point it at an array of data and an array of column definitions (like most other analogous components).
@etovian You don't need to create a database. That's just used in the example because the example needs to generate a lot of random data to display.
You barely even have to use Observables. They're used in the examples because they massively simplify manipulating the data in response to user events and are generally very powerful and flexible. If you just want to render an array once, you can use Observable.of(myArrayOfValues) and you don't have to touch rxjs again. If you want to render it more than once,
// component
_dataSubject = new BehaviorSubject<any[]>([])
constructor() {
this.dataSource = new MyDataSource(this._dataSubject)
}
updateValues(myArray: any[]) {
this._dataSubject.next(myArray)
}
// MyDataSource
constructor(private _data: BehaviorSubject<any[]>) { }
connect() {
return this._data.asObservable()
}
@willshowell Thanks for the tip! I sort of got this working:
export class MyDataSource extends DataSource<any[]> {
data = [
{ firstName: 'Mike' },
{ firstName: 'Amy' },
{ firstName: 'Jillian' },
{ firstName: 'Juliette' }
];
constructor() {
super();
}
connect (): Observable<any[]> {
return Observable.of(this.data);
}
disconnect ( ): void {
}
}
The only problem is that the data doesn't load when the component using the dataSource initializes. Oddly, if I click elsewhere on the page (not even inside the component), then table displays the data. Here's all of the code:
import { Component, OnInit, ViewChild } from '@angular/core';
import { CdkTable, DataSource } from '@angular/cdk';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/observable/fromEvent';
import { InvitationService } from "../services/invitation.service";
@Component ( {
selector: 'app-sandbox',
templateUrl: './sandbox.component.html',
styleUrls: [ './sandbox.component.css' ]
} )
export class SandboxComponent implements OnInit {
dataSource: MyDataSource | null;
displayedColumns = ['firstName'];
@ViewChild('table')
table: CdkTable<any>;
constructor(private invitationService: InvitationService) {
}
ngOnInit() {
this.dataSource = new MyDataSource();
//this.dataSource.connect();
}
}
export class MyDataSource extends DataSource<any[]> {
data = [
{ firstName: 'Mike' },
{ firstName: 'Amy' },
{ firstName: 'Jillian' },
{ firstName: 'Juliette' }
];
constructor() {
super();
}
connect (): Observable<any[]> {
return Observable.of(this.data);
}
disconnect ( ): void {
}
}
And the template:
<md-table
#table
[dataSource]="dataSource">
<ng-container cdkColumnDef="firstName">
<md-header-cell *cdkHeaderCellDef> First Name </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.firstName}} </md-cell>
</ng-container>
<md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
<md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
@willshowell Oddly, this is working exactly as expected:
import { Component, OnInit } from '@angular/core';
import { DataSource } from '@angular/cdk';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/observable/fromEvent';
import { InvitationService } from "../services/invitation.service";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
@Component ( {
selector: 'app-sandbox',
templateUrl: './sandbox.component.html',
styleUrls: [ './sandbox.component.css' ]
} )
export class SandboxComponent implements OnInit {
dataSource: MyDataSource | null;
dataSubject = new BehaviorSubject<any[]>([]);
displayedColumns = ['firstName'];
constructor(private invitationService: InvitationService) {
this.invitationService.getInvitations().subscribe({
next: value => this.dataSubject.next(value)
});
}
ngOnInit() {
this.dataSource = new MyDataSource(this.dataSubject);
}
}
export class MyDataSource extends DataSource<any[]> {
constructor(private subject: BehaviorSubject<any[]>) {
super ();
}
connect (): Observable<any[]> {
return this.subject.asObservable();
}
disconnect ( ): void {
}
}
Since this much better represents how I'd do things in production, I'm not necessarily concerned with why the code from my previous post isn't working. Thanks again for your help! You definitely saved me some continued hair-pulling.
I can certainly get by with this, but I think that the option to work directly with an array would help folks get up and running much more quickly, even if the DataSource is a more performant solution.
Thanks to all the devs for their hard work!
@etovian your first issue looks like https://github.com/angular/material2/issues/6199 which is resolved and will be a part of the next release.
Also an array-based data source that is plug-and-play is in the works https://github.com/angular/material2/pull/6182, though it's not clear which direction that PR will take
@willshowell What does your getInvitations() method look like in your InvitationService service?
constructor ( private http: Http ) { }
getInvitations (): Observable<Invitation[]> {
return this.http.get ( this.invitationUrl ).map ( response => response.json () );
}
I am not getting any error but the data from web API is not rendering in datatable. Only columns are displayed.
Below is my code:
` import { Component, OnInit, ViewChild } from '@angular/core'; import { UserService } from '../Service/user.service'; import { IUser } from '../Model/user'; import { DBOperation } from '../Shared/enum'; import { Observable } from 'rxjs/Rx'; import { Global } from '../Shared/global'; import { ManageUser } from './manageuser.component'; import { MdDialog, MdDialogRef } from '@angular/material'; import { UserFilterPipe } from '../filter/user.pipe'; import { DataSource } from "@angular/cdk/collections";
@Component({ templateUrl: 'app/Components/userlist.component.html' })
export class UserListComponent implements OnInit {
users: IUser[];
user: IUser;
dataSource: userDataSource;
displayedColumns = ['FirstName', 'LastName'];
constructor(private _userService: UserService) { }
ngOnInit(): void {
this.LoadUsers();
}
LoadUsers(): void {
this._userService.get(Global.BASE_USER_ENDPOINT)
.subscribe(users => { this.users = users }
);
this.dataSource = new userDataSource(this.users);
}
}
export class userDataSource extends DataSource
constructor(private _users: IUser[]) {
super();
}
connect(): Observable<IUser[]> {
return Observable.of(this._users);
}
disconnect() { }
} `
Below is my html
`
<ng-container mdColumnDef="LastName">
<md-header-cell *mdHeaderCellDef> Last Name </md-header-cell>
<md-cell *mdCellDef="let element"> {{element.LastName}} </md-cell>
</ng-container>
<md-header-row *mdHeaderRowDef="displayedColumns"></md-header-row>
<md-row *mdRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
</div>
Not getting where exactly the issue is.
@etovian Can you provide an example of filtering such table?
@theunreal try https://github.com/angular/material2/tree/master/src/material-examples/table-filtering
EXPLAIN ME please, HOW does it work? When I add new item to data source's array – table doesn't show it immediately. It shows no changes until I click on header for sorting or paginator and only after that table will re-render.
@Shrralis I think the key in this line - https://github.com/angular/material2/blob/master/src/material-examples/table-filtering/table-filtering-example.ts#L68