Component link in angular 1.5

Angular In build proposals with 1.5 components, there are usually output bindings for invoking methods on root controllers.

Say I have a root component and two child components.

<root> <child-1></child-1> <child-2></child-2> </root> 

He would like to respond to a button click on component one by reading the value on component 2, and then doing something in the root.

For example, child-1 is a directive that wraps a drawing library that attaches a drawing to its DOM node and has a variable to control this drawing.

child-2 has a button. When it is clicked, the data from the child-1 variable must be passed to root, which does something with it.

In particular, child-1 wraps var graph2d = new vis.Graph2d(container, dataset, options); . Later, I would like to get some information from graph2d and pass it to root in order to do something with it.

It boils down to: how can components respond to events fired by other components? The input and output suggestions do not seem to cover this scenario.

+5
source share
1 answer

In angular 1.5, you can use require and / or property bindings (input / output) for communication.

If you use the require property, your root component will publish the api, and your child component will receive a link to the controller:

 angular.module('app').component('child1', { bindings: {}, require: {api: '^root'}, //your <root> component template: '', controller: controller }); 

Then you can use the methods of the root component in the child component:

 $ctrl.api.addWatchedBook(); 

This is the function of the root component controller:

 $ctrl.addWatchedBook = addWatchedBook; function addWatchedBook(bookName){ booksWatched.push(bookName); } 

Here is a complete architectural overview : Component Communications

+3
source

Source: https://habr.com/ru/post/1247205/


All Articles