Reputation: 1752
How would you add a component to a View from the ViewModel. For example, I have the following:
I have a service injected into a component. Then from the component I fetch data and when I get the response I set the data
property to the fetched data. After this I would like to mount the component to the View with the fetched data as a bindable.
this.service.get()
.then(response => response.json())
.then(data =>{
this.data = data.results
//Mount element to View here: <component data.bind="data"></component>
})
Im asking this question because if I set the value when fetched and on the View to this:
<component data.bind="data"></component>
It passes an empty object. I have tried using the service on the canActivate
and activate
methods.
Component:
export class Component{
@bindable data
bind(){
console.log(this.data)
}
}
Upvotes: 0
Views: 258
Reputation: 10887
I copied your code in to a gist and ran it on gist.run here: https://gist.run/?id=04907ff8d8b6d8b4aee625669d8571a3
It runs as expected for me. I even updated it to set the data inside a promise.
Now, if you want to be notified when the data
property changes, you'll need to implement a function called ${propertyName}Changed(newValue, oldValue)
so in this case, dataChanged(newValue, oldValue)
. I created a separate gist to show how you might want to change your code: https://gist.run/?id=34a01ca3f600470691d5b91c9131f33b
You'll notice in my code I didn't use the newValue
and oldValue
parameters. I did this on purpose to let you know that Aurelia still sets the property value. The callback is just there to let your code do stuff when the property value changes.
Upvotes: 2
Reputation: 878
The "data" field being bound to is a field on the ViewModel using your component, not a field in your component.
Upvotes: 0