To use our new component, we will need to add LoginComponent to app.module.ts. The Angular CLI automatically added our new component to the nearest parent module.
Login Component HTML
Our login component needs two inputs for username and password, plus a button to start the login.
[(ngModel)] = "username" binds the value of the input to a local variable in the component.
(click)="submit()" maps the click event on the button to the submit function
Login Component
Component Decorator
selector - the html name for the component
template - inline template
templateUrl - url to template
styles - inline styles
stylesUrl - url to styles file
providers - objects to be injected into component
Component Providers - be cautious about declaring providers at the component level. It creates a new instance of the service (which are singleton by design) and makes it more complex to mock the service.
Component Hierarchy
All applications have a root component that Angular bootstraps the application with
Each page should be a component
Pages usually are comprised of child components
Create child components to reduce complexity or when functionality appears in multiple pages
Lifecycle Hooks
Angular component instances have a lifecycle as Angular creates, updates, and destroys them. A component can implement them, e.g., export class LoginComponent implements OnInit
ngOnInit
Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.
Called once, after the firstngOnChanges().
ngOnChanges
Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChangesobject of current and previous property values.
Called before ngOnInit() and whenever one or more data-bound input properties change.
ngAfterViewInit
Respond after Angular initializes the component's views and child views / the view that a directive is in.
Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks.
Called just before Angular destroys the directive/component.
The lifecycle hook interfaces are optional - since JavaScript doesn't support interfaces, Angular calls any lifecycle methods that are declared. It's considered good practice to implement the interfaces to declare your intent.