By using & binding in child component we can run function that is part of parent components controller. I am strugling to do the same in oposite direction - when something happens in parent component, child component runs function.
I have mapComponent which is direct child of mainComponent. mapComponent displays fullscreen Google Map(using NgMap) with some markers. mainComponent handles login and registration. If users start registration I need to run function in mapComponent that removes all markers and attaches map event so that user could click on map to show were he lives and those coordinates could be saved on registration.
Just for example that wouldnt be to complex, here is code from plunker I found while searching stackoverflow:
var app = angular.module('plunker', []);
app.controller('RootController', function() {});
app.component('parentComponent', {
template: `
<h3>Parent component</h3>
<a class="btn btn-default btn-sm" ng-click="$ctrl.click()">Notify Child</a>
<span data-ng-bind="$ctrl.childMessage"></span>
<child-component on-change="$ctrl.notifiedFromChild(count)" message="$ctrl.message"></child-component>
`,
controller: function() {
var ctrl = this;
ctrl.notifiedFromChild = function(count) {
ctrl.childMessage = "From child " + count;
}
ctrl.click = function() {
ctrl.message = Math.random()
}
},
bindings: {}
});
app.component('childComponent', {
template: `
<h4>Child component</h4>
<a class="btn btn-default btn-sm" ng-click="$ctrl.click()">Notify Parent</a>
<span>{{$ctrl.parentMessage}}</span>
`,
controller: function() {
var ctrl = this;
ctrl.counter = 0;
ctrl.click = function() {
ctrl.onChange({
count: ++ctrl.counter
});
}
},
bindings: {
onChange: '&',
parentMessage: '<message'
}
});
In this example by clicking button in parent component I can change parentMessage value in child component through data binding. However I would want to find a way for child component change this value byself when parent component asks to do it.