Skip to content

Commit

Permalink
Merge branch 'main' into docs/control-value-accessor
Browse files Browse the repository at this point in the history
  • Loading branch information
RobbyRabbitman authored Jan 24, 2024
2 parents c8c02e4 + d6c5fbc commit 810958a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
24 changes: 23 additions & 1 deletion docs/src/content/docs/utilities/Signals/connect.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: connect
description: ngxtension/connect
entryPoint: connect
badge: stable
contributors: ['enea-jahollari']
contributors: ['enea-jahollari', 'josh-morony', 'chau-tran']
---

`connect` is a utility function that connects a signal to an observable and returns a subscription. The subscription is automatically unsubscribed when the component is destroyed. If it's not called in an injection context, it must be called with an injector or DestroyRef.
Expand All @@ -16,6 +16,8 @@ import { connect } from 'ngxtension/connect';

It can be helpful when you want to have a writable signal, but you want to set its value based on an observable.

#### Connect with observables

For example, you might want to have a signal that represents the current page number, but you want to set its value based on an observable that represents the current page number from a data service.

```ts
Expand All @@ -31,6 +33,8 @@ export class AppComponent implements OnDestroy {
}
```

#### Connect with observables not in an injection context

You can also use it not in an injection context, but you must provide an injector or DestroyRef.

```ts
Expand All @@ -54,6 +58,24 @@ export class AppComponent implements OnDestroy {
}
```

#### Connect with other signals

This is useful when you want to have a writable signal, but you want to update its value based on another signal that represents the current state of that value.
For this to work, the second argument must be a callback function that includes a signal call inside of it.

```ts
@Component()
export class AppComponent implements OnDestroy {
private dataService = inject(DataService);

pageNumber = signal(1);

constructor() {
connect(this.pageNumber, () => this.dataService.state().pageNumber);
}
}
```

## Object Signal

There are cases where we construct a single `Signal` to store a state object. `connect` can also work with object signals
Expand Down
1 change: 1 addition & 0 deletions libs/ngxtension/connect/src/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ function parseArgs(
return [args[0] as Observable<unknown>, null, null, false, null];
}

// to connect signals to other signals, we need to use a callback that includes a signal call
if (typeof args[0] === 'function') {
return [null, null, null, false, args[0] as () => unknown];
}
Expand Down

0 comments on commit 810958a

Please sign in to comment.