Reputation: 45
I am making a test table from a class created. Current class should generate a table of available data in my html file. But I do not see anything generated.
I am using Angular 5.
Expected table:
type1 Car
type2 Plane
type3 Truck
Component File:
import { Component, OnInit } from '@angular/core';
import { mService } from '../Dash/Dash.service';
import { m } from '../Dash/Dash.model;
@Component({
selector: 'app-m',
templateUrl: './m.component.html',
styleUrls: ['./m.component.css'],
providers: [mService]
})
export class mComponent implements OnInit {
mServ: m[]
constructor(private _mService: mService) {
}
ngOnInit() {
this.mServ= this._mService.GetData(true);
}
}
Service file
import { Injectable } from '@angular/core';
import { m } from '.Dash.model;
@Injectable()
export class mService {
//sourc - not currently in use
GetData(sour: boolean): m{
var viewModel = new m();
view.wheels= [
"Car", "Plane", "Truck"
];
view.type= [
"type1", "type2", "type3"
];
return view;
}
constructor() { }
}
Model file
import { Injectable } from '@angular/core';
@Injectable()
export class m{
public wheels: Array<string>;
public type: Array<string>;
constructor() { }
}
HTML
<table>
<tbody>
<tr *ngFor='let mServ&& mServ.length'>
<td>{{ mServ.wheels}}</td>
<td>{{ mServ.type}}</td>
</tbody>
</table>
Upvotes: 0
Views: 6194
Reputation: 958
How about this: in your component. I have removed the service call, but assigning it to a value amounts to the same effect. //service.ts import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
public getData(source: boolean): Array<any> {
return [{
'wheels' : ['plane', 'truck', 'car'],
'types': ['type1', 'type2', 'type3']
}];
}
}
App Component
//app.component.ts
import { Component } from '@angular/core';
import { MyService } from './service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
public view: any;
constructor(private svc: MyService) {
this.view = this.svc.getData(true);
}
}
Html Template
<table>
<tbody>
<tr *ngFor='let s of view'>
<!-- <td>
{{s | json}}
</td> -->
<span *ngFor='let it of s.wheels; index as i' [attr.data-index]="i">
<td>{{s.wheels[i]}}</td>
<td>{{s.types[i]}}</td>
</span>
</tbody>
</table>
Upvotes: 0
Reputation: 222582
ngFor syntax above is wrong, it should iterate among objects not length
<tr *ngFor='let mServObj of mServ'>
if you want to check for *ngIf, you could do as,
<tbody>
<ng-container *ngIf= "mServ&& mServ.length > 0">
<tr *ngFor='let mServObj of mServ'>
<td>{{ mServ.wheels}}</td>
<td>{{ mServ.type}}</td>
</tr>
</tbody>
Upvotes: 1