Reusable component with binding and route data

Now, let's refactor the viewUser component, so that we can reuse it in multiple contexts. One where it can load its own data using a resolve guard, suitable for a master/detail view and another, where we can bind the current user to it, as we have done in the Review step of the multi-step input form we built in the prior section:

  1. Update viewUser component with the following changes:
src/app/user/view-user/view-user.component.ts
...
import { ActivatedRoute } from '@angular/router'

export class ViewUserComponent implements OnChanges, OnInit {
...
constructor(private route: ActivatedRoute) {}

ngOnInit() {
if (this.route.snapshot && this.route.snapshot.data['user']) {
this.currentUser = User.BuildUser(this.route.snapshot.data['user'])
this.currentUser.dateOfBirth = Date.now() // for data mocking purposes only
}
}
...

We now have two independent events. One for ngOnChanges, which handles what value gets assigned to this.currentUser, if this.user has been bound to. ngOnInit will only fire once, when the component is first initialized or has been routed to. In this case, if any data for the route has been resolved then it'll be assigned to this.currentUser.

To be able to use this component across multiple lazy loaded modules, we must wrap it in its own module.

  1. Create a new shared-components.module.ts under app:
src/app/shared-components.module.ts
import { NgModule } from '@angular/core'
import { ViewUserComponent } from './user/view-user/view-user.component'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { FlexLayoutModule } from '@angular/flex-layout'
import { CommonModule } from '@angular/common'
import { MaterialModule } from './app-material.module'

@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
FlexLayoutModule,
MaterialModule,
],
declarations: [ViewUserComponent],
exports: [ViewUserComponent],
})
export class SharedComponentsModule {}

  1. Ensure that you import SharedComponentsModule module into each feature module you intended to use ViewUserComponent in. In our case, these will be User and Manager modules.
  2. Remove ViewUserComponent from the User module declarations

We now have the key pieces in place to begin the implementation of master/detail view.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.19.185