irossimoline / angular4-material-table

Angular 4 table based on @angular/cdk table structure, to allow row insertion, edition, validation and deletion.
MIT License
55 stars 25 forks source link

Setting default values in FormControl #6

Closed Tomerco89 closed 6 years ago

Tomerco89 commented 6 years ago

Hi,

I am trying to set a default value for a cell when creating a new row, but for some reason i cant make it work... any help will be appreciated.

irossimoline commented 6 years ago

Hi @Tomerco89,

The way I see it, you can try something like this:

table.component.html

<mat-table [dataSource]="dataSource">
  <!-- columns -->
  <ng-container matColumnDef="actionsColumn">
    <mat-header-cell *matHeaderCellDef>
      <button (click)="addNewWithDefaultValue()">Create</button>
    </mat-header-cell>
    <mat-cell *matCellDef="let row">
      <button *ngIf="!row.editing" (click)="row.startEdit()">Edit</button>
      <button *ngIf="row.editing"
 (click)="row.confirmEditCreate()">Confirm
          </button>
      <button (click)="row.cancelOrDelete()">Cancel</button>
    </mat-cell>
  </ng-container>
  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

table.component.ts

// Component definition...

// Method that is called from "Create" button.
addNewWithDefaultValue() {
  dataSource.createNew();
  const row = dataSource.getRow(-1); // new Row's id is always -1
  // Here you load the default data for the new row.
  row.currentData.field1 = 'default field1';
}

I'm not sure if you can use form control's default value to create rows with default values, because an object is created in the table, and that object is created empty intentionally.

If you still can't find a way to do it, please share some code where I can start with.

irossimoline commented 6 years ago

Hi @Tomerco89 ,

If you have additional questions please open a new issue.