Important Note: It is not recommended to bind data directly from a service object. It is better to retrieve the data from the service, store it in a local variable within the component, and then work on that data. Here's an example:
Component TypeScript file:
export class XYZComponent implements OnInit {
dataFromService: any;
constructor(public service: DataService) { }
ngOnInit() {
this.dataFromService = this.service.caseDetails;
}
}
The corresponding HTML for the component:
{{dataFromService | json}}
{{dataFromService.address.state | json}}
<form>
<input name='test' type="text" [(ngModel)]="dataFromService.address.state">
</form>
No changes are needed in the Service code.
This implementation has been tested and proven successful.
Service TypeScript file:
@Injectable()
export class DataService {
public caseDetails = {
partyId: '',
address: {
state: 'mystate',
city: '',
zip: '',
street: ''
}
};
}
Component TypeScript file:
@Component({
selector: 'xyz',
templateUrl: 'xyz.component.html'
})
export class XYZComponent {
constructor(public service: DataService) { }
}
Component HTML file:
{{service.caseDetails | json}}
{{service.caseDetails.address.state | json}}
<form>
<input name='test' type="text" [(ngModel)]="deskService.caseDetails.address.state">
</form>
It's important to note that instead of using this
, you should use
<input type="text" [(ngModel)]="serviceObj.caseDetails.address.state">
In order for this to function properly, make sure that serviceObj
is declared as public
.