I currently have a parent component and several children component.
<parent-component>
<child-component ng-data="$ctrl.object.fieldone"></child-component>
<child-component ng-data="$ctrl.object.fieldtwo"></child-component>
...
<button ng-click='$ctrl.setEdit();">Edit</button>
</parent-component>
Each child component will either: display the data using a series of divs/spans representing View Mode or display the data using form elements representing Edit Mode.
The parent component has a button which triggers editMode.
What is the best way to inform the child components that the state is Edit Mode? There seem to be a lot of different ways of passing this state across: the parent could Broadcast or the parent's editMode variable could be binded to the children component. Is there even a better way beyond these two.
Assume well over 20-30 child components and that these components will be used in different views.
Thanks,
Theoretically, broadcast should only be used for application wide events. Imagine login/logout notifications, websockets events...etc.
If you start to use broadcast for small events, you will end up with tons of events everywhere in your app and you won't know which one is triggered by what.
If your app is small enough and consists of only a parent component and children where the main event is to toggle an edition mode boolean, then it's fine to use broadcast.
For anything bigger than that you can obviously use bindings instead. In your particular case it feels a little heavy on the html elements to add an attribute to each of your 30 children.
The fact you use a parent / children hierarchy means you can make use of require. By requiring the parent in each of your child component, you can automatically use its properties. This way you can pass an editMode variable and it's scalable if you need to pass more data in the future.
var parent = {
controller: ParentController,
template:`
<button ng-click="$ctrl.editionMode = !$ctrl.editionMode">Edition</button>
<br><br>
<child></child>
`
}
function ParentController() {
this.editionMode = false;
}
var child = {
require: { parent: '^^parent' },
controller: ChildController,
template: `
<input type="text" ng-model="$ctrl.value" ng-if="$ctrl.parent.editionMode">
<span ng-if="!$ctrl.parent.editionMode">{{$ctrl.value}}</span>
`
}
function ChildController() {
this.value = "edit me";
}
angular.module('myApp', []);
angular.module('myApp')
.component('parent', parent)
.controller('ParentController', ParentController)
.component('child', child)
.controller('ChildController', ChildController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<div ng-app="myApp">
<parent></parent>
</div>