I have an object declared in my service :
public caseDetails = {
partyId: '',
address: {
state: '',
city: '',
zip: '',
street: ''
}
}
I need to bind the objects to a input box. Here is what I could do
<input type="text" [(ngModel)]="this.serviceObj.caseDetails.partyId">
Here is the what I can't do
<input type="text" [(ngModel)]="this.serviceObj.caseDetails.address.state">
I could bind if the object declared in my component. But I can't bind to a service object. Here is the error details:
ERROR TypeError: Cannot read property 'state' of undefined at Object.eval [as updateDirectives]
Note: it not recommended way to bind data from service object directly, it's better you get data from service and store in local variable to component and do work on that. An example:
component.ts :
export class abcComponent implements OnInit {
datafromService:any;
constructor(
public service: DataService
) { }
ngOnInit() {
this.datafromService = service.caseDetails;
}
}
html of component then :
{{datafromService|json}}
{{datafromService.address.state|json}}
<form>
<input name='test' type="text"
[(ngModel)]="datafromService.address.state">
</form>
Service-code there is no change.
Below is working tried and tested at my end.
service.ts :
@Injectable()
export class DataService {
public caseDetails = {
partyId: '',
address: {
state: 'mystate',
city: '',
zip: '',
street: ''
}
}
}
component.ts :
@Component({
selector: 'abc',
templateUrl: 'abc.component.html'
})
export class abcComponent {
constructor(
public service: DataService
) { }
}
component.html :
{{service.caseDetails|json}}
{{service.caseDetails.address.state|json}}
<form>
<input name='test' type="text"
[(ngModel)]="deskService.caseDetails.address.state">
</form>
There is issue that you used this
, it should be
<input type="text" [(ngModel)]="serviceObj.caseDetails.address.state">
for this to work serviceObj
need to be public
so it will work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.