In this video, Aviv Ben-Yosef introduces the concept of lifecycle hooks and goes into detail about the initialization hook. Learn how setup should be performed in components.
- [Instructor] With Angular 1.6, component controls now have a few lifecycle hooks. These are places intended to make it clear where certain component management logic should be located. Perhaps, the most common lifecycle hook is the initialization hook called '$onInit'. It is the right place for all the setup code and management a component needs. For quite a while, Angular style guides have recommended adding some kind of 'Init' function to controls anyway.
This is another step in making a common practice into the explicitly right way of doing things, and also, matching up Angular 1.x with the way things are done in Angular 2. Let's open 'TodoJS' in the exercise files. First, I'll add an empty 'onInit' method. (typing) Note that the name can't be changed, as is for all lifecycle hooks.
Then, I go over the controller. All the initialization logic of the controller should be moved to sit inside the new 'onInit' method. (typing) After doing so, the control function should be composed only of method definitions and controller variable declarations. In case a control does not have any initialization to perform, it is safe to skip implementing 'onInit' at all.
All lifecycle hooks are optional. The '$onInit' hook has another role in Angular 1.6. By default, Angular only guarantees that a components bindings be ready and initialized when 'onInit' is called and not earlier. This is a breaking change for a lot of the components or directives out there, which is why, if you recall, I recommended setting a configuration to disable it previously. After converting all the components in a project to use '$onInit', it's safe to go to the config block and remove the setting that disables this.
Aviv Ben-Yosef kicks off the course by explaining what's different in Angular 1.6, as well the different motives for upgrading. Next, he walks through how to safely upgrade an existing app. He covers going from controllers to directives, as well as component lifecycle hooks. He also goes into the architectural changes in Angular, such as one-way data flow and immutability. To wrap up, he discusses how to properly test components.
- Deciding to upgrade an existing app
- Upgrading to Angular 1.6
- Removing standalone controllers
- Using directives as route targets
- Converting a controller's code
- Converting a controller's template
- Comparing directives and components
- Converting a directive
- Reviewing the concept of one-way binding