Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data from parent to child angular.js components [duplicate]

I have parent component:

(function () {
  angular.module('app.module')
    .component('parentComponent', {
      templateUrl: 'parent.html',
      controllerAs: 'vm',
      controller: function ($scope) {
      this.$onInit = () => {
        $scope.parentData = 'test'
      }
  })
})()

child component

(function () {
  angular.module('app.module').component('childComponent', {
  templateUrl: 'child.html',
  controllerAs: 'vm',
  controller: function () {
  this.$onInit = () => {
  }
 }
})
})()

parent.html

<child-component></child-component>

child.html

<p>{{parentData}}</p>

So I want to have access to parentData in my child component for display string 'test' in my child component. How can I do it? I read something about bindings but I don't know how to use it in this example.

Thanks for any suggestions.

like image 218
emka26 Avatar asked Oct 22 '25 03:10

emka26


1 Answers

Use one-way < binding:

<child-component in-data="$ctrl.parentData"></child-component>

The child component:

app.component("childComponent", {
    bindings: {
        inData: '<',
    },
    template: `
        <div>{{$ctrl.inData}}</div>
    `,
})

The DEMO

angular.module("app",[])
.component("parentComponent", {
    template: `
        <fieldset>
            Inside parent component<br>
            parentData={{$ctrl.parentData}}
            <child-component in-data="$ctrl.parentData"></child-component>
        </fieldset>
    `,
    controller: function () {
        this.$onInit = () => {
            this.parentData = 'test'
        };
    },
})
.component("childComponent",{
    bindings: {
        inData: '<',
    },
    template: `
        <fieldset>Inside child component<br>
            inData={{$ctrl.inData}}
        </fieldset>
    `,
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
    <parent-component>
    </parent-component>
<body>

For more information, see

  • AngularJS Developer Guide - Component-based application architecture
  • AngularJS Comprehensive API Reference - scope
like image 63
georgeawg Avatar answered Oct 25 '25 00:10

georgeawg