Declaring optional dependencies
Angular introduced the @Optional
decorator, which allows us to deal with dependencies that don't have a registered provider associated with them. Let's suppose that a dependency of a provider is not available in any of the target injectors responsible for its instantiation. If we use the @Optional
decorator, during the instantiation of the dependent provider a value of the missing dependency will be passed as null
.
Now, let's take a look at the following example:
abstract class SortingAlgorithm { abstract sort(collection: BaseCollection): Collection; } class BaseCollection { getDefaultSort(): SortingAlgorithm { // get some generic sorting algorithm... return null; } } class Collection extends BaseCollection { public sort: SortingAlgorithm; constructor(sort: SortingAlgorithm) { super(); this.sort = sort || this.getDefaultSort(); } } @Component({ selector: 'app', template: "Open your browser's console" }) class AppComponent...