Is it possible to change provider of component in Angular Material Dialog?

708 views Asked by At

I have a component with InjectionToken and custom provider to get data from store. In base usage of the component I need to provide data with "user logins", but in dialog I need to get "user names" with the same component. Is it possible to pass other injector or somehow use other provider in component with Material Dialog?

InjectionToken

const USERS = new InjectionToken<Observable<string[]>>(
  'A stream with user's login or name'
);

Providers

const userLoginProvider: Provider = {
  provide: USERS,
  deps: [ Store ],
  useFactory: (store: Store) => store.pipe(select(userLoginSelector)),
};

const userNameProvider: Provider = {
  provide: USERS,
  deps: [ Store ],
  useFactory: (store: Store) => store.pipe(select(userNameSelector)),
};

Component class

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.scss' ],
  providers: [userLoginProvider],
})
export class UsersComponent implements OnInit {

  constructor(@Inject(USERS) public users$: Observable<string[]>) { }

  public ngOnInit(): void {
  }

}

Component template

<div *ngIf="users$ | async as users">
  <div *ngFor="let user of users">
    // show list of logins or names
  </div>
</div>

Usage of the dialog somewhere in other component:

const dialog = this.matDialog.open(UsersComponent);

I suggested something like this:

const namesInjector = Injector.create({
      providers: [
        {
          provide: USERS,
          useValue: userNameProvider,
        },
      ],
      parent: this.injector,
    });

const dialog = this.matDialog.open(UsersComponent, {
 // usage of custom injector somewhere there
});

I know that I can use custom ComponentFactoryResolver in MatDialogConfig but I have no idea how to do it and use with custom injector. By the way, I can use data property in MatDialogConfig to change users$ in component but it looks like a kludge.

0

There are 0 answers