Synopsis: I am trying to iterate over an array that is returned as part of an object. The object has three properties 2 string, 1 array. I want to iterate over the array i my html but can't seem to get it to populate. I can get both strings to show, but cannot figure out how to iterate the inner array for values.
Policy.ts
import { Document } from './Document';
export interface Policy {
insuredName: string;
policyNumber: string;
documents: Document[];
}
Document.ts
export interface Document {
url: string,
docType: string
}
I bind the model("policy") in my parent component
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
policy: any = {};
constructor(private policyService: PolicyService, private alertify: AlertifyService) { }
ngOnInit() {
}
loadPolicy() {
this.policyService.getPolicy(this.policy.policyNumber).subscribe((res) => {
this.policy.insuredName = res.insuredName;
this.policy.policyNumber = res.policyNumber;
this.documents = res.documents;
}, error => {
this.alertify.error(error);
})
}
I pass the data to my child component
Search.component.html
<app-documentList [policy]=policy></app-documentList>
and then bind it in the child
export class DocumentListComponent implements OnInit {
@Input() policy: Policy;
ngOnInit() {
}
but when I finally try the iteration all I get is the first property (insuredName) and nothing for the *ngFor
<div>
<div class="test">
<p>{{policy.insuredName}}</p>
<h2 *ngFor="let doc of policy.documents">{{doc.url}}</h2>
</div>
</div>
Try replacing this.documents = res.documents;
with this.policy.documents = res.documents;
.
Looks like you are binding the result to a wrong variable.
Also you might not have to assign values manually. You could do the following
import { Policy } from './Policy';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
policy: Policy = {};
constructor(private policyService: PolicyService, private alertify: AlertifyService) { }
ngOnInit() {
}
loadPolicy() {
this.policyService.getPolicy(this.policy.policyNumber).subscribe((res: Policy) => {
this.policy = res;
}, error => {
this.alertify.error(error);
});
}
}