Skip to content

Commit

Permalink
fix(component): reset form-bound captcha value after component destru…
Browse files Browse the repository at this point in the history
…ction

This is a back-port of 8.x.x fix for #201
  • Loading branch information
DethAriel committed Jul 22, 2021
1 parent fab99aa commit 9e5c5e7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/recaptcha/recaptcha-value-accessor.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,34 @@ export class RecaptchaValueAccessorDirective implements ControlValueAccessor {
/** @internal */
private onTouched: () => void;

private requiresControllerReset = false;

constructor(private host: RecaptchaComponent) {}

public writeValue(value: string): void {
if (!value) {
this.host.reset();
} else {
// In this case, it is most likely that a form controller has requested to write a specific value into the component.
// This isn't really a supported case - reCAPTCHA values are single-use, and, in a sense, readonly.
// What this means is that the form controller has recaptcha control state of X, while reCAPTCHA itself can't "restore"
// to that state. In order to make form controller aware of this discrepancy, and to fix the said misalignment,
// we'll be telling the controller to "reset" the value back to null.
if (
this.host.__unsafe_widgetValue !== value &&
Boolean(this.host.__unsafe_widgetValue) === false
) {
this.requiresControllerReset = true;
}
}
}

public registerOnChange(fn: (value: string) => void): void {
this.onChange = fn;
if (this.requiresControllerReset) {
this.requiresControllerReset = false;
this.onChange(null);
}
}
public registerOnTouched(fn: () => void): void {
this.onTouched = fn;
Expand Down
14 changes: 14 additions & 0 deletions src/recaptcha/recaptcha.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,20 @@ export class RecaptchaComponent implements AfterViewInit, OnDestroy {
}
}

/**
* ⚠️ Warning! Use this property at your own risk!
*
* While this member is `public`, it is not a part of the component's public API.
* The semantic versioning guarantees _will not be honored_! Thus, you might find that this property behavior changes in incompatible ways in minor or even patch releases.
* You are **strongly advised** against using this property.
* Instead, use more idiomatic ways to get reCAPTCHA value, such as `resolved` EventEmitter, or form-bound methods (ngModel, formControl, and the likes).å
*/
public get __unsafe_widgetValue(): string | null {
return this.widget != null
? this.grecaptcha.getResponse(this.widget)
: null;
}

/** @internal */
private expired() {
this.resolved.emit(null);
Expand Down

0 comments on commit 9e5c5e7

Please sign in to comment.