Angular: Material Table Convert API Array For Material Table
I am trying to retrieve an array of json data from an API and present it as a material table. However am facing problems, it reads that the attributes cannot be found.
How can I solve this?
lead.service.ts
getAllLeads(): Observable<any> {
return this.http.get(this.base_url, {
headers: this.httpHeaders
});
}
leadtable.component.ts
export class Lead {
business_id: Business [];
genre_id: Genre [];
language_id: Language [];
activity: string;
phone_no: number;
event_title: string;
name: string;
email: string;
city: string;
org_name: string;
partner_type: string;
college_activity: string;
college_music_contest: string;
college_name: string;
budget: string;
prize: string;
other: string;
gig_type: string;
date_of_event: Date;
event_city: string;
}
ngOnInit(): void {
this.getLeads()
console.log(this.dataSource); //undefined
this.displayedColumns = ['name', 'partner_type', 'city'];
}
getLeads = () => {
this.leadApi.getAllLeads().subscribe(
data => {
this.lead_list = data;
console.log(this.lead_list);
},
error => {
console.log(error);
}
)
}
1 answer
-
answered 2020-12-01 21:36
Becike
Can you share your html code too? Angular's Material table sometimes can be tricky.
Your console.log(this.datasource) is undefined because of the async call.
Try to use MatTableDataSource, you can pass in observables too, and it will be easier to use for example paginator, or sorter later.
See also questions close to this topic
-
Creating two value range slider from Angular material native component
I need a two value range slider for my app, however none of the packages that I've looked at on NPM etc are 100% suitable for what I need. The Angular Material slider is the most suitable, however it doesn't allow for two values to be used on a single slider.
To get around this, I've had an idea of placing one slider on top of the other, to give the impression of one slider with two values. This works well, and has a smooth behaviour which is one of the requirements that I wanted my slider to have.
However, I would also like to add a bar in between the two slider thumbs, so that the selected range is highlighted and visible. The native slider does have this, but since it only allows one value the highlight starts from 0 and extends to the value of the slider.
Instead I want to have the highlight between the upper and lower values of the thumbs on the slider. But I have no idea how to add this to it. So I was wondering if someone could help me out. I'm not entirely sure if I'd need to add a new element on top of the bar that adjusts to the size between the two thumbs or if I'd have to do something different.
Alternatively if anyone knows how to make NGX-slider allow a smooth step like the angular material slider that would be the best solution and I'd love to hear it. https://www.npmjs.com/package/@angular-slider/ngx-slider
https://angular-9-material-starter-5ueh7p.stackblitz.io
Code so far
<mat-slider class="slider-left"></mat-slider> <mat-slider class="slider-right"></mat-slider> .slider-right { position: relative; left: -128px; } ::ng-deep .mat-slider-track-fill { background-color: rgba(0, 0, 0, 0.26) !important; } ::ng-deep .mat-slider-track-background { background-color: rgba(0, 0, 0, 0.26); }
-
Angular 10 form action not getting variable
I am creating a form in angular, used from a 3rd party, which needs to redirect away from my site for a payment and back.
I have added their sample code (the form which does a post) into my angular app and added a formGroup, and an action to the form (the action is the url I want to redirect to).
<form [formGroup]="tdsvt" (ngSubmit)="onSubmit2021" method="post" id="redirectForm" action="{{redirectUrl}}"> <input type="hidden" name="id" formControlName="reqID" /> </form>
I have changed the action to the variable that is needed, but it does not redirect and it stays blank. I have tried doing a normal post request and subscribe like so:
return this.http.post<any>(redirectUrl, data);
But I am hit with a CORS issue as it is a total different URL.
How can I get the action to work as a variable and redirect? Or if I shouldn't use an action, what's the best method around this?
Thank you
-
Child route with fragment
I have a page with a side menu, each side menu item has a routerLink that sends a different fragment. I want to know if it is possible that this new route with the fragment has a child route.
Example:
Side menu:
<button type="button" routerLink="['/pageA']" fragment="frag">btn side menu</button>
On click this button, the route would look like this: http://localhost:4200/#/pageA#frag
Content Page
<button type="button" routerLink="['child-a']">A</button> <button type="button" routerLink="['child-b']">B</button> <router-outlet></router-outlet> // Here son A or son B will be loaded
And when click on button A, the route would look like this: http://localhost:4200/#/pageA#frag/child-a
page-routing.module.ts
const routes: Routes = [ { path: '', component: PageAComponent, children: [ { path: 'child-a', component: ChildAComponent, }, { path: 'child-b', component: ChildBComponent, }, ], }, ];
-
Passing 2D arrays to a function to print out a matrice
I want to make a program, in which I pass a 2D array to a function, and the function prints the contents of the array in a matrix format. However, in my code, the function is printing only 1, also why am I getting the following warning "pointer to a function used in arithmetic"?
#include <iostream> using namespace std; void grid(int size[][3]){ for(int x=0;x<3;x++){ for(int y=0;y<3;y++){ cout<<grid[x][y]; } cout<<endl; } } int main(){ int mak[3][3]={ {1,2,3}, {4,5,6}, {7,8,9} }; grid(mak); }
-
How to remove item from multidimensional, associative array in PHP
I have a multi dimensional, associative array. I'm trying to find a way to remove spesific items from the array, regardless of their position.
The array is used for building the navigation menu on a website. Sub items will always be in an array called "children" within its parent item. The key "children" is not present for items that have no children, if that makes things easier.
"menuid" is the item's id in the database, but since there are multiple types of items (pages, category pages, galleries, urls and so forth), the same menuid may occur multiple times. I want to be able to remove items by "menuid" and "menutype".
I'm able to delete an item based on menuid alone, but only from the root array:
$key = array_search(15, array_column($array, 'menuid')); unset($array[$key]);
I prefer to do it with a function, but I have the same problem here. This will also only remove items if they're in the root of the array.
function removeItem($array, $menutype, $menuid) { foreach ($array as $key => $value) { if (is_array($value)) { if (isset($value['menutype']) && isset($value['menuid']) && $value['menutype'] == $menutype && $value['menuid'] == $menuid) { unset($array[$key]); } } } return $array; } $removeItem = removeItem($array, 'simplepage', 11);
I have not found a way to delete items from anywhere in the array based on both "menutype" and "menuid".
Here's an example of the array. What would I do to delete the item with menuid 13 and menutype "posts_category"?
Array ( [0] => Array ( [menutarget] => _parent [menulink] => / [rewritename] => Home [menutype] => url [menuid] => 2 [id] => Home ) [1] => Array ( [id] => Category 3 [menuid] => 15 [menutype] => posts_category [rewritename] => Category_3 [menulink] => [menutarget] => _parent ) [2] => Array ( [id] => Page 1 [menuid] => 11 [menutype] => page [rewritename] => page_1 [menulink] => [menutarget] => _parent [children] => Array ( [0] => Array ( [id] => Category 1 [menuid] => 13 [menutype] => posts_category [rewritename] => Category_1 [menulink] => [menutarget] => _parent [children] => Array ( [0] => Array ( [id] => Category 2 [menuid] => 14 [menutype] => posts_category [rewritename] => Category_2 [menulink] => [menutarget] => _parent ) ) ) ) ) [3] => Array ( [menutarget] => _parent [menulink] => [rewritename] => Videotest [menutype] => page [menuid] => 10 [id] => Videotest ) )
-
Printing Two Multidimensional Arrays in PHP with Custom Loop Side by Side
I have two multidimensional arrays in PHP that sometimes become 4 levels deep.
These arrays are built from JSON APIs and need to be printed side by side in a table in order to be compared on a daily basis.
So far I have used a custom recursive loop to print them because array_walk_recursive wouldn't print them side in table tags with the ability to customize the loop.
This is my loop:
function pretty_dump($arr, $d=1){ if ($d==1) echo "<pre>"; // HTML Only if (is_array($arr)){ foreach($arr as $k=>$v){ for ($i=0;$i<$d;$i++){ echo "_"; } if (is_array($v)){ echo '<span class="red">'. $k.PHP_EOL . "</span>"; Pretty_Dump($v, $d+1); } else { echo '<span class="label"><strong>' . $k . "</strong>" ."</span>"."\t".'<span class="value">'.$v.PHP_EOL. "</span>"; } } } if ($d==1) echo "</pre>"; // HTML Only
Then I call the array like this, inside the table:
<tr> <td> <? pretty_dump ($result); ?> </td> <td> <? pretty_dump ($result2); ?> </td> <td> <? pretty_dump ($result3); ?> </td> </tr>
My issue here is that I need to compare all three arrays ($result, $result2, $result3) with the keys of $result (first array). I need the table to be setup in a way so that if there isn't a value for a certain key in $result there should be an NA or blank in the column next to $result.
For example if $result2 doesn't have a value for a corresponding $result key, it should print a NA in that td tag for $result2.
-
How can I display a select list within an Angular Material table?
How can I display a select list within an Angular Material table?
error:
TS2339: Property 'element' does not exist on type 'MyaccountComponent'. <mat-option *ngFor="let role of element.validRoles" [value]="role.value">
I get the same error if I change
element.validRoles
tovalidRoles
too.Component:
export class MyaccountComponent implements OnInit { displayedColumns: string[] = ['email', 'role', 'rolestatus', 'validRoles']; dataSource = []; ngOnInit(){ this.getAllUsers(); } constructor(private userService: UserService) { } getAllUsers(){ const obs = this.userService.getAllRegisteredUsers(); obs.subscribe(data => { console.log(data.users); this.dataSource = data.users }); } }
Template:
<ng-container matColumnDef="validRoles"> <th mat-header-cell *matHeaderCellDef> Assign Role</th> <mat-form-field appearance="fill"> <mat-label>Roles</mat-label> <mat-select> <mat-option *ngFor="let role of element.validRoles" [value]="role.value"> {{role.viewvalue}} </mat-option> </mat-select> </mat-form-field> </ng-container>
My data is in the format:
data.users.validRoles = [ {value: "admin", viewvalue: "Admin"} ];
-
Trigger AngularComponent-constructor on startup with PreLoadingStrategy
The goal: trigger a component residing in a module, so my subscription in the ctor of the component is activated. I'm using PreloadAllModules as a preloadingStrategy. But it's not happening.
I need to subscribe to some events in de constructor of my FriendsComponent. the setup is like this:
FriendsComponent is shown in the template of the SocialComponent, which is part of the SocialModule.
social.component.html
<div> <friends-component></friends-component> </div>
the SharedModule declares the FriendsComponent. AppModule imports SharedModule, RouterModule for AppModule is like this:
{ path: 'social', component: SocialModule, children: [ { path: 'friends', component: FriendsComponent } ] },
I think the problem is because the FriendsComponent is not part of a router-outlet? Can it be done without a router-outlet?
If a module would be pre- or eager loaded, would it automatically trigger the constructors (and the subscription)? Is the issue with my preloading strategy?
I have tried adding: data:{preload:true} to the paths declared in routermodule.
Everything works fine, when the user activates the SocialModule (for instance by clicking on a button with a routerLink to social/friends), but I want it activated on startup (just not shown on any html) I'm working with Angular Ivy, but think I'm still missing the points. Any help is appreciated