theming / Function

withThemeBuilder

Generic types:Builder

Creates a token generation specification, which specifies the target ThemeBuilder and relevant configurations to be passed to the builder.

See Also

Presentation

function withThemeBuilder(
  name: string,
  builder: ProviderToken<Builder>,
  config:
    | ThemeBuilderConfigOf<Builder>
    | Observable<ThemeBuilderConfigOf<Builder>>,
): Observable<ThemeBuilderComposition>;

Returns

Parameters

NameTypeDescription
name
string

The name that will be passed to the theme builder.

builder
ProviderToken<Builder>

The token that can be used to retrieve the theme builder

config
ThemeBuilderConfigOf<Builder> | Observable<ThemeBuilderConfigOf<Builder>>

The configuration object that will be passed to the theme builder.

Usage Notes

A builder class can be passed to the builder parameter because constructor classes are valid tokens for dependency injection. It is worthy noting that you need to make sure that there is a provider for the token. This function does not register providers for the token.

provide({ token: ColorBuilder, useClass: MyColorBuilder }),
withThemeBuilder('color', ColorBuilder, { primaryColor: PRIMARY_COLOR }),

An observable can be passed as the config parameter, in which case the theme is expected to be updated on every value emission.

withThemeBuilder(
  'color',
  ColorBuilder,
  observePreferredColorScheme().pipe(
    map((isDark) => ({ primaryColor: PRIMARY_COLOR, dark: isDark })),
  ),
);

In order to gain access to the injection context, use the defer RxJS operator, which defers the invocation of the observable factory until the observable is subscribed during the environment initialization, where an injection context is available.

withThemeBuilder(
  'color',
  ColorBuilder,
  defer((schemeObserver = inject(PreferredColorSchemeObserver)) =>
    schemeObserver
      .observe()
      .pipe(map((isDark) => ({ primaryColor: PRIMARY_COLOR, dark: isDark }))),
  ),
);