I am trying to create a dynamic menu using a json response from server but I am getting this error:
MenuComponent.html:4 ERROR TypeError: Cannot read property 'subscribe' of undefined at MatMenuTrigger.push../node_modules/@angular/material/esm5/menu.es5.js.MatMenuTrigger.ngAfterContentInit
and when I click the buttons it says this:
ERROR TypeError: Cannot read property 'createEmbeddedView' of undefined at ViewContainerRef_.push../node_modules/@angular/core/fesm5/core.js.ViewContainerRef_.createEmbeddedView
I am guessing that buttons can't created because json response is not ready but I don't know how to fix it.
Component.ts
export class MenuComponent implements OnInit {
branchList: Branches = new Branches(); //read somewhere that I need to initialize, not sure
ngOnInit(): void {
this.http.get('http://demo8635782.mockable.io/branches').subscribe((data: any) => {
if (data === null) {
console.log('api request returns empty!');
}
this.branchList = data;
});
}
constructor(private breakpointObserver: BreakpointObserver, private http: HttpClient) {
}
}
Template.html
<button mat-button [matMenuTriggerFor]="branchesMenu">Branches</button>
<mat-menu #branchesMenu="matMenu">
<div *ngFor="let branch of branchList?.branches">
<button mat-menu-item [matMenuTriggerFor]="branch?.name">{{branch.name}}</button>
</div>
</mat-menu>
branchList: Branches = new Branches();
tobranchList: Branches;
? does it change the error? ... also I've never seen a type declared for ngOnInit- there is no need – Kyle Burkett