Skip to content

Instantly share code, notes, and snippets.

@jorroll
Created November 4, 2019 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorroll/846dadf0814a15de677da3029f4a1a13 to your computer and use it in GitHub Desktop.
Save jorroll/846dadf0814a15de677da3029f4a1a13 to your computer and use it in GitHub Desktop.
@Directive({
selector: '[myFormControl]',
})
export class MyFormControlDirective {
@Input('myFormControl') providedControl!: FormControl;
control = new FormControl('');
private changesSubscriptions: Subscription[] = [];
private subscriptions: Subscription[] = [];
constructor(
@Inject(NG_CONTROL_ACCESSOR)
private accessor: ControlAccessor,
) {
// Sync this directive's control with the ControlAccessor's control
this.subscriptions.push(
concat(
this.accessor.replayState(),
this.accessor.events,
).subscribe(this.control.source),
this.control.events.subscribe(this.accessor.source),
);
}
ngOnChanges(changes: { providedControl: SimpleChange }) {
this.control.source.next({
source: this.control.id,
processed: [],
type: 'ControlAccessor',
label: 'PreCleanup',
});
this.changesSubscriptions.forEach(sub => sub.unsubscribe());
this.changesSubscriptions = [];
this.control.source.next({
source: this.control.id,
processed: [],
type: 'ControlAccessor',
label: 'PreInit',
});
// Sync/Link the providedControl with this directive's control. As a reminder,
// this directive's control is already linked with the ControlAccessor (meaning
// that the providedControl will be linked with the ControlAccessor).
this.changesSubscriptions.push(
concat(
this.providedControl.replayState(),
this.providedControl.events,
).subscribe(this.control.source)
this.control.events.subscribe(this.providedControl.source),
);
this.control.source.next({
source: this.control.id,
processed: [],
type: 'ControlAccessor',
label: 'PostInit',
});
}
ngOnDestroy() {
this.changesSubscriptions.forEach(sub => sub.unsubscribe());
this.subscriptions.forEach(sub => sub.unsubscribe());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment