How to add data dynamically to mat-table dataSource?

后端 未结 7 1468
既然无缘
既然无缘 2020-12-08 06:39

I have data streaming from backend and i see it printing in console now i am trying to push event to dataSource its throwing error dataSource is not defined. Ca

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 07:05

    I was stuck in same problem while creating select row and apply some action over rows data. This solution for your problem

    imports..................
    import { MatTableDataSource } from '@angular/material';
    @component({ ...
    
    export class StreamComponent implements OnInit {
    // Initialise MatTableDataSource as empty
    dataSource = new MatTableDataSource();
    
    constructor() {}
    ...
    // if you simply push data in dataSource then indexed 0 element remain undefined
    // better way to do this as follows
     this.dataSource.data = val as any;
    
      // for your problem
    
       ngOnInit() {
      // ** important note .... I am giving solution assuming the subscription data is array of objects. Like in your case stream and in second event(parameter as callback)
        this.streamService.getAllStream().subscribe(stream => {
           // do it this way
            this.dataSource.data = stream as any;
         // note if you simply put it as 'this.dataSource.data = stream' then TS show you error as '[ts] Type 'string' is not assignable to type '{}[]''
        });
        this.socket.on('newMessage', (event) => {
            console.log('Datasource', event);
              // for this value
           // this.dataSource.MatTableDataSource.filteredData.push(event);   // I couldn't get what you are doing here 
         // SO try to explain what you are getting in this callback function val as event parameter ????????????????? 
         // but you can get it this ways
    
           this.dataSource.filteredData = event as any;
        });
      }
    

    Hope this will help you . If you have any question just ping me.

提交回复
热议问题