-
-
Save jorroll/846dadf0814a15de677da3029f4a1a13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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