Angular 4 table based on @angular/cdk table structure, to allow row insertion, edition, validation and deletion.
npm install angular4-material-table@angular/cdk data-table, also used in @angular/material table.
@angular/cdk/collections DataSource in order to include a row structure, allowing row creation, inline row edition, deletion and validation.
npm install angular4-material-table
angular4-material-table:
@angular/cdk data-table.
datasource with an instance of TableDataSource.
TableDataSource allows you to have some row related methods and data to implement add/edit/remove elements:
typescript
class TableElement {
id: number;
editing: boolean;
currentData?: T;
originalData: T;
source: TableDataSource;
validator: FormGroup; // Used only in reactive forms.
delete(): void;
confirmEditCreate(): boolean;
startEdit(): void;
cancelOrDelete(): void;
isValid(): boolean; // Used only in reactive forms.
}
`
`typescript
class TableDataSource {
constructor(
data: T[],
dataType?: new () => T,
validatorService?: ValidatorService,
config = { prependNewElements: false, suppressErrors: false });
datasourceSubject: Subject;
updateDatasource(data: T[], options = { emitEvent: true }): void;
createNew(): void;
getRow(id: number): TableElement;
}
`
$3
Angular 4 material table use example:
!Example of angular4-material-table use
See this package in action
#### Optional libraries
Optional libraries used in the example:
`
"@angular/material": "2.0.0-beta.12",
"@angular/forms": "4.4.4", // <- For inline validation
"font-awesome": "4.7.0"
`
#### person-list-reactive-forms.component.html
`html
Name
Age
`
#### person-list-template-driven.component.html
`html
Name
Age
`
#### person-list.component.ts
`typescript
@Component({
selector: 'app-person-list',
providers: [
{provide: ValidatorService, useClass: PersonValidatorService }
],
templateUrl: './person-list.component.html',
})
export class PersonListComponent implements OnInit {
constructor(private personValidator: ValidatorService) { }
displayedColumns = ['name', 'age', 'actionsColumn'];
@Input() personList;
@Output() personListChange = new EventEmitter();
dataSource: TableDataSource;
ngOnInit() {
this.dataSource = new TableDataSource(this.personList, Person, this.personValidator);
this.dataSource.datasourceSubject.subscribe(personList => this.personListChange.emit(personList));
}
}
class Person {
name: string;
age: number;
}
@Injectable()
class PersonValidatorService implements ValidatorService {
getRowValidator(): FormGroup {
return new FormGroup({
'name': new FormControl(null, Validators.required),
'age': new FormControl(),
});
}
}
``