micronyks
micronyks

Reputation: 55443

Common code handling in angular2 like angular1

Angular1

<div ng-app="myApp" ng-controller="AppCtrl">
      <ui-view>
           
      <ui-view>
</div>

Here different views will be injected in ui-view.
Let's say home.html is injected so homeCtrl will come into pic.
I can consider AppCtrl is parent when homeCtrl is child.
Moreover when homeCtrl is initialized, AppCtrl is also called once as Parent/Child scenario.
So throughout application I can put common code in AppCtrl

Angular2

Boot.ts <===== shouldn't constructor be called everytime? [This is just my thought]
|_____Home.ts
|_____Aboutus.ts

Boot.ts

export class BootCmp{
  constructor(){
     console.log('Should this run everytime??')
  }
}

Which is best way to put common code?
sharedService?
Or some other mechanism is there?

Upvotes: 0

Views: 217

Answers (2)

Marc
Marc

Reputation: 1300

What i read in your question and your comments are two concerns: One is Compoment Communication and the other is CommonCode-Initialsation.

  1. Component Communication:

If you "forget" @Input and @Output, it is possible to use a service for communication between parent and child.

See the MissionControlExample in the Angular 2 cookbook for example:

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

If you don´t want to use a shared service, use EventEmitter for Example.
See: Parent listens for child event (same link as MissionControlExample)

One of the advantages of Angular 2 is the suport of the HTLM5 webcomponent concept, so .html is a part of a component as template element.

  1. CommonCode Initialisation
    Depends on the CommonCode. If it is App specific, initialse it in your AppComponent, if it is Component specific inialise it in the Component. It depends... on your code.

To answer more concrete, please share your code in your question.

Upvotes: 0

Sasxa
Sasxa

Reputation: 41294

Root component of your app is "constructed" once - constructor() is called when you bootstrap the application. The rest of the components are created and destroyed based on your app logic, for example using router or ngIf.

Not sure what you consider "common code" but you can plan with this in mind...

Upvotes: 0

Related Questions