Reputation: 3357
I am new to angular and i am trying to make a dynamic table to display data.
Right i have it (somewhat working) with static data.
I was inspired from this example here: https://stackblitz.com/angular/lrpjroljdly?embed=1&file=app/table-selection-example.html
const COLUMN_DATA: IClusterColumnOrient[] = [...Array(10).keys()].map((_, index) =>({
columnName: (Math.random() + 1).toString(36).substring(7),
schemaName: (Math.random() + 1).toString(36).substring(7),
columnType: (Math.random() + 1).toString(36).substring(7),
id: (Math.random() + 1).toString(36).substring(7),
tableName: (Math.random() + 1).toString(36).substring(7),
databaseName: (Math.random() + 1).toString(36).substring(7),
databaseId: (Math.random() + 1).toString(36).substring(7)
}))
@Component({
selector: 'column-search',
templateUrl: './column-search.component.html',
styleUrls: ['./column-search.component.scss'],
})
export class ColumnSearchComponent implements OnInit{
displayedColumns: string[] = ['select', 'columnName', 'columnType', 'tableName', 'schemaName'];
selection = new SelectionModel<IClusterColumnOrient>(true, []);
@ViewChild('searchInput', { static: true }) searchInput: ElementRef;
columnsData: IClusterColumnOrient[]
isSearching: boolean
columns: string[]
dataSource = new MatTableDataSource<IClusterColumnOrient>(COLUMN_DATA);
This works fine, but when i want to use dynamic data i initialize an empty array, and what for user input to query my backend dynamically.
constructor(private httpClient: HttpClient){
this.isSearching = false
this.columnsData = []
//Hardcoded as of now, we can import and parse from backend in the future
}
ngOnInit(){
console.log(this.columnsData)
fromEvent(this.searchInput.nativeElement, 'keyup').pipe(
//Find type for js event
map((event: any) =>{
return event.target.value
}),
debounceTime(700),
distinctUntilChanged(),
.....
When i try to substitute the COLUMN_DATA
with this.columnData
i get an error like such:
Property 'columnsData' is used before its initialization.
How can i substitute this with dynamic data?
Upvotes: 0
Views: 460
Reputation: 4597
The error message is revealing an important clue here. You only declare the property columnsData: IClusterColumnOrient[]
without initializing it. You take care of the initialization of this variable inside of your constructor
, but at the time you create the MatTableDataSource
it is still uninitialized, only declared. You can only declare the data source as you do with the columnsData
property
dataSource: MatTableDataSource<IClusterColumnOrient>;
and then move your datasource initialization inside the constructor as well to avoid this problem.
constructor(private httpClient: HttpClient){
this.isSearching = false
this.columnsData = []
this.dataSource = new MatTableDataSource<IClusterColumnOrient>(this.columnsData);
}
Upvotes: 1