角度可编辑材料表

时间:2017-12-21 22:53:21

标签: angular user-interface

我正在使用Material表,并且很难找到可编辑Material表的示例。我找到了一个例子,但我不知道如何适应我现有的代码..他是我发现的最佳链接 链接:https://www.npmjs.com/package/angular4-material-table

plunker:https://plnkr.co/edit/9kZfUW?p=preview

这是我的代码,如果有人使用其他类型的可编辑表格,我也会对任何建议开放。在我尝试添加可编辑功能之前,我的表格正在显示&正确地进行排序和搜索。现在我需要让它可编辑

HTML

<mat-table #table [dataSource]="dataSource" matSort>
                        <ng-container matColumnDef="ID">
                            <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
                            <mat-cell *matCellDef="let row">
                                {{row.ID}}

                            </mat-cell>
                        </ng-container>
                        <ng-container matColumnDef="Comment">
                            <mat-header-cell *matHeaderCellDef mat-sort-header> Commment </mat-header-cell>
                            <mat-cell *matCellDef="let row">

                                <mat-form-field floatPlaceholder="{{ row.editing ? 'float' : 'never'}}">
                                    <input [formControl]="row.validator.controls['Comment']" [readonly]="!row.editing" placeholder="Comment" [(ngModel)]="row.currentData.Comment" matInput>
                                </mat-form-field>
                            </mat-cell>
                        </ng-container>
                        <ng-container matColumnDef="actionsColumn">
                            <mat-header-cell *matHeaderCellDef>
                                <button mat-icon-button color="accent" (click)="dataSource.createNew()"><i class="fa fa-plus mat-icon"></i></button>
                            </mat-header-cell>
                            <mat-cell *matCellDef="let row">
                                <button *ngIf="!row.editing" mat-icon-button color="primary" focusable="false" (click)="row.startEdit()">
                                    <i class="fa fa-pencil mat-icon"></i>
                                </button>
                                <button *ngIf="row.editing" mat-icon-button color="primary" focusable="false" (click)="row.confirmEditCreate()">
                                    <i class="fa fa-check mat-icon"></i>
                                </button>
                                <button mat-icon-button color="primary" focusable="false" (click)="row.cancelOrDelete()">
                                    <i class="fa fa-times mat-icon"></i>
                                </button>
                            </mat-cell>
                        </ng-container>
                        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
                        <mat-row *matRowDef="let row; columns:displayedColumns"></mat-row>
                    </mat-table>
                    <mat-paginator #paginator
                                   [pageSize]="10"
                                   [pageSizeOptions]="[5, 10, 20]">
                    </mat-paginator>

接口

export interface IToDoList {

    ID: number,
    Comment: string
}

component.ts

export class DashboardComponent implements OnInit {
    toDoList: IToDoList[] = null;
    dataSource = new MatTableDataSource();
    @ViewChild(MatPaginator) paginator: MatPaginator;
    @ViewChild(MatSort) sort: MatSort;
    displayedColumns = ['Comment'];

     ngOnInit(): void { 
        this.GetToDoList(this.userID);
    }
    onOpen() {

        this._dashboardService.delBSAFollowup(this.selectedRowID).subscribe(() => {
          //  this.showMessage('File has been uploaded successfully!', 'alert alert-success');
           this.getBSAFollowup();

        },
          error => console.log('Upload File: '));

    }

    GetToDoList(ID: string) {
        this._dashboardService.getToDoList(ID)
            .subscribe(
            data => {
              //  this.toDoList = data.result;
                //this.dataSource = new MatTableDataSource(data.result);
                this.dataSource.data = data.result;
                  },
            error => console.log('GetControls Method: ' + <any>error, 'alert alert-danger'));
    }

     ngAfterViewInit() {

        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    }
    applyFilter(filterValue: string) {
        filterValue = filterValue.trim(); // Remove whitespace
        filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
        this.dataSource.filter = filterValue;
    }

}

service.ts

import { IToDoList } from './toDoList';
@Injectable()

export class DashboardService {


    baseAPIURL: string;
    constructor(private _http: Http) {



    }

    getToDoList(psnlUID:string) {


        return this._http.get(environment.BASE_API_URL + 'XXXXX/' + ID)
            .map((response: Response) => response.json())
            .do(data => console.log('All' + JSON.stringify(data)))
            .catch(this.handleError);

    }


    private handleError(error: Response) {
        return Observable.throw(error.json().error || 'Server Error');
    }
}

*************** *****更新******************************************** ******

HTML
               <mat-table #table [dataSource]="dataSource" matSort>
                        <ng-container matColumnDef="ID">
                            <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
                            <mat-cell *matCellDef="let row">

    {{row.currentData.id}}


                            </mat-cell>
                        </ng-container>
                        <ng-container matColumnDef="Comment">
                            <mat-header-cell *matHeaderCellDef mat-sort-header> Commment </mat-header-cell>
                            <mat-cell *matCellDef="let row">
                                <mat-form-field floatPlaceholder="{{ row.editing ? 'float' : 'never'}}">
                                    <input matInput [formControl]="row.validator.controls['Comment']" placeholder="Comment" [(ngModel)]="row.currentData.Comment">
                                </mat-form-field>
                                                 </mat-cell>
                        </ng-container>
                        <ng-container matColumnDef="actionsColumn">
                            <mat-header-cell *matHeaderCellDef>
                                <button mat-icon-button color="accent" (click)="dataSource.createNew()"><i class="fa fa-plus mat-icon"></i></button>
                            </mat-header-cell>
                            <mat-cell *matCellDef="let row">
                                <button *ngIf="!row.editing" mat-icon-button color="primary" focusable="false" (click)="row.startEdit()">
                                    <i class="fa fa-pencil mat-icon"></i>
                                </button>
                                <button *ngIf="row.editing" mat-icon-button color="primary" focusable="false" (click)="row.confirmEditCreate()">
                                    <i class="fa fa-check mat-icon"></i>
                                </button>
                                <button mat-icon-button color="primary" focusable="false" (click)="row.cancelOrDelete()">
                                    <i class="fa fa-times mat-icon"></i>
                                </button>
                            </mat-cell>
                        </ng-container>
                        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
                        <mat-row *matRowDef="let row; columns:displayedColumns"></mat-row>
                    </mat-table>
                    <mat-paginator #paginator
                                   [pageSize]="10"
                                   [pageSizeOptions]="[5, 10, 20]">
                    </mat-paginator>

TodoItemValidatorService.ts

@Injectable()
export class TodoItemValidatorService implements ValidatorService {
    getRowValidator(): FormGroup {
        return new FormGroup({

            'Comment': new FormControl(),
        });
    }
}

component.ts

    class TodoItem {
        ID: number;
        Comment: string;
    }
    export class DashboardComponent implements OnInit {
     @Output() personListChange = new EventEmitter<TodoItem>();
    dataSource: TableDataSource<TodoItem>;
    @Output() personListChange = new EventEmitter<TodoItem>();

        @Input() todoList = [];

        constructor(private _dashboardService:  private todoItemValidator: ValidatorService) {

            _appParams.AdminPSNLUID.subscribe((val) => {
                this.userID = val;
            });

        }

      ngOnInit(): void {

            this.GetToDoList(this.userID);
            this.dataSource = new TableDataSource<any>(this.todoList, TodoItem, this.todoItemValidator);

    this.dataSource.datasourceSubject.subscribe(todoList => this.personListChange.emit(todoList));


        }

    GetToDoList(ID: string) {
            this._dashboardService.getToDoList(ID)
                .subscribe(
                data => {

                     this.dataSource.updateDatasource(data.result);
                      },
                error => console.log('GetControls Method: ' + <any>error, 'alert alert-danger'));
        }


    }

服务

@Injectable()

export class DashboardService {


    baseAPIURL: string;
    constructor(private _http: Http) {



    }

    getToDoList(psnlUID:string) {


        return this._http.get(environment.BASE_API_URL + 'XXXXX/' + ID)
            .map((response: Response) => response.json())
            .do(data => console.log('All' + JSON.stringify(data)))
            .catch(this.handleError);

    }


    private handleError(error: Response) {
        return Observable.throw(error.json().error || 'Server Error');
    }
}

1 个答案:

答案 0 :(得分:1)

您应该按照以下步骤操作:

  1. 使用您要存储的数据创建一个类。我建议您使用lowerCamelCase作为变量:

    public class Comment {
      id: number;
      comment: string;
    }
    
  2. 使用您指定的类实例化新的TableDataSource。在您指定的示例中,您正在实施MatTableDataSource

    this.dataSource = new TableDataSource<any>([], Comment);
    // The array is empty, if you want to have initial elements just pass a filled array.
    
  3. 如果您按照建议使用lowerCamelCasing,请记住 更改您的html文件。

  4. 下次您遇到特定软件包的问题时,可以直接在package's repo中打开问题,我很乐意在那里回答。

    编辑:

    我建议您阅读angular4-material-table的repo readme.md,在那里您可以找到行(TableElement)和TableDataSource的可用方法和属性。如果该信息不够,我会鼓励您navigate into the code并查看方法说明。