2

I am upgrading a large Angular 1.6 App and we have number of components which use 'require' to get access to parent component's controller. AngularJS component looks like:

 var tileTextbox = {
        template: '<ignore>',
        controller: TileTextboxController,
        bindings: {
            field: '<',
            notifyError: '&',
            context: '<',
            onRemoteFieldAction: '&',
            onChange: '&'
        },
        require: {
            formsCtrl: '^gsForm' ----> What should this be replaced with in Angular component?
        }
    };

I found @ViewChild which gives Parent access to Child but I am looking for other way around. I know we could refactor an use some sort of shared service but at this point I am just looking for minimal refactor. From Angular's documentation @ https://angular.io/guide/upgrade it does look like your component can use 'require' but just don't know how

pateketu
  • 451
  • 2
  • 8
  • To add to above, the parent component is AngularJS, this is an Hybrid app with some components being moved to Angular – pateketu Nov 30 '18 at 10:14

2 Answers2

1

require equivalent in angular is Host. You can use Host decorator to acquire the parent component instance. For the same you have to mention parent component/directive/service name inside child component consturctor.

constructor(@Host() private gsForm: GsForm) {
   //here you will have access to parent directive gsForm
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

From AngularJS Docs:

Intercomponent Communication

Directives can require the controllers of other directives to enable communication between each other. This can be achieved in a component by providing an object mapping for the require property. The object keys specify the property names under which the required controllers (object values) will be bound to the requiring component's controller.

Essentially this is required to share data between two Components. There are multiple ways of doing that in Angular.

  1. You could create a SharedService and inject it in both the Angular Components. Set data from one component and retrieve data from the other.
  2. You could use @Input properties to pass data from Parent to Child.
  3. You could use @Output properties to pass data from Child to Parent.

There are many other ways of sharing data between parent and child components. ViewChild etc for instance. But the above three are the most straight-forward ways.

Community
  • 1
  • 1
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110