How to add a row in my custom table on top?

Viewed 58

I have written a custom table in which you can add rows with a button. How can I set it so that the newly inserted row is displayed at the top of my table?

My Code:

// For the form
  kagListForm: FormGroup;
  rows: FormArray;
  submitted = false;

 // Variables for Data Table
  public columns = [];
  private all = false;
  public index: number;
  public originalData: any = [];

 public displayedColumns: EditColumns[] = [
    { attribute: 'kagNumber', name: 'Kag-Nr.', object: null },
    { attribute: 'kagText', name: 'Bezeichnung', object: null }
  ];
ngOnInit() {

    // To initialize data table
    this.columns = this.displayedColumns.map(c => c.attribute);

    // KagList form
    this.kagListForm = this.formBuilder.group({
      rows: this.formBuilder.array([])
    });
  }
// To add new row in the kagList
  addRow() {
    const formArray = this.kagListForm.get('rows') as FormArray;
    const start = (this.rows && this.rows !== null) ? this.rows.controls.length : 0;
    for (let i = start; i < (start + 1); i++) {
      const rowData = {
        id: new FormControl(`new-${i}`),
        kagNumber: new FormControl(''),
        kagText: new FormControl(''),
      };
      const createRow = this.formBuilder.group(rowData);
      formArray.push(createRow);
    }
    this.rows = formArray;
  }
1 Answers

Instead of going with FormArray.push() you could go with FormArray.insert(0) which would add the row at the top (as per the doc).

Related