0

to display data from observable array one can do:

Component:

myObject: ko.observableArray([{name: 'test'}]),

Html:

<ul data-bind="foreach: myObject">
     <li data-bind="text: name"></li>
</ul>

Display:

enter image description here

How can I Display a simple json object not an array like the above E.G:

Component:

myObject: ko.observable({name: 'test'}),

HTML

<li data-bind="text: myObject.name"></li>

Display enter image description here

What am i missing?

2

The template would need to look like this:

<div data-bind="text: myObject().name"></div>

but after doing so you will run into the next issue. Because updating the observable values like:

this.myObject().name = 'new value';

won't work. You would need to assign a whole new object to this.myObject. like f.e. by using

var newObj = this.myObject();
newObj.name = 'new value';
this.myObject(newObj);

another possibility would be to not make the whole object an observable, but instead declaring the object properties as observables like:

myObject: {
  name: ko.observable('value')
},

so you can access the value in the template by using:

<div data-bind="text: myObject.name()"></div>

or assigning new values to it by using:

this.myObject.name('new value');
  • I think last option is good for me I don't have many properties. THX. – Juliano Vargas May 27 '20 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.