Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass object to component

I have created a component that needs to have a reference to the object for which the component was created. I didn't make to work and all my trials have failed. Below, I try to describe the intention.

The component definition would maybe look like this:

angular
    .module('myModule')
    .component('myComponent', {
        templateUrl: "template.html",
        controller: [
            MyController
        ],
        bindings: {
            myObject: '='
        }
    });

function MyController(myObject) {
    var vm = this;

    vm.myObject = myObject;
}

In a service I would like to create my object like this:

function createMyObject(args) {
        var myObject = {some: data};

        myObject.ref = "<my-component myObject='{{myObject}}'></my-component>";
        return myObject;
    }

Question

How can I pass data to angular component tag? Do I have to switch back to a component directive to make it work?

Any ideas are greatly appreciated. Thank you.

like image 304
Amio.io Avatar asked Feb 28 '16 11:02

Amio.io


People also ask

How do you pass an object to a component in React?

Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component. Copied!

How do you pass an object between angular components?

There are several ways how Angular components can pass data around: Using @Input and @Output. By injecting parent component through constructor or child components through @ViewChild , @ViewChildren , @ContentChild , @ContentChildren and directly calling component's API.


1 Answers

Solution 1

In your template:

<my-component key='$ctrl.myObject'></my-component>

In code:

angular
    .module('myModule')
    .component('myComponent', {
        templateUrl: "template.html",
        controller: [
            'objectService'
            MyController
        ],
        bindings: {
            key: '=' // or key: '<' it depends on what binding you need
        }
    });

function MyController(myObject, objectService) {
    var vm = this;

    vm.myObject.whatever(); // myObject is assigned to 'this' automatically
}

Solution 2 - via Component Bindings

Component:

angular
.module('myModule')
.component('myComponent', {
    templateUrl: "template.html",
    controller: [
        'objectService'
        MyController
    ],
    bindings: {
        key: '@'
    }
});
function MyController(myObject, objectService) {
    var vm = this;

    vm.myObject = objectService.find(vm.key);
}

Usage:

function createMyObject(args) {
    var myObject = {key: ..., some: data};

    myObject.ref = "<my-component key='" + myObject.key + "'></my-component>";
    return myObject;
}
like image 200
Amio.io Avatar answered Nov 13 '22 07:11

Amio.io