0

I have a simple table that shows static data, however, I have issues for showing it via input.

The question is how can I pass the data to the material2 table using item input.

export class InvoiceItemComponent implements OnInit {
  displayedColumns = ['id', 'description', 'amount', 'taxGroup'];
  exampleDatabase = new ExampleDataBase();
  dataSource: ExampleDataSource | null;
  @Input() item;

  constructor() {}

  ngOnInit() {
    console.log(this.exampleDatabase.data);
    this.dataSource = new ExampleDataSource(this.exampleDatabase);
  }
}

export class ExampleDataBase {
  dataChange: BehaviorSubject<any> = new BehaviorSubject([]);
   get data(): InvoiceItem[] {
    return [ // works fine with static data, cannot figure out how to pass it via @Input() item which is the required data
      {
        id: 1,
        description: 'your desc here',
        amount: 20,
        taxAmount: 20,
        taxGroup: {
          id: 1,
          name: 'tax group name'
        }
      },
    ];
  }

  constructor() {
    this.dataChange.next(this.data);
  }
}

export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDataBase) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<InvoiceItem[]> {
    console.log(this._exampleDatabase.dataChange);

    return this._exampleDatabase.dataChange;
  }

  disconnect() {}
}
2

1 Answer 1

1

Maybe try something like this

export class InvoiceItemComponent implements OnInit {

  displayedColumns = ['id', 'description', 'amount', 'taxGroup'];

  dataSource: InvoiceItemDataSource | null;

  @Input() set items(vals: InvoiceItem[]) {
    this.itemSubject.next(vals);
  }

  /** Emits a new array of invoice items whenver `@Input() items` changes */
  itemSubject = new BehaviorSubject<InvoiceItem[]>([]);

  constructor() {}

  ngOnInit() {
    // Pass the item subject as an observable which can be connected directly
    // to the data source's `connect()`
    this.dataSource = new InvoiceItemDataSource(this.itemSubject.asObservable());
  }
}

export class InvoiceItemDataSource extends DataSource<any> {
  constructor(private data: Observable<InvoiceItem[]>) {
    super();
  }

  connect(): Observable<InvoiceItem[]> {
    return this.data;
  }

  disconnect() {}
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the answer. I am gonna deep dive into your answer now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.