Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(forms): support for dynamic control change #1074

Merged
merged 8 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion projects/angular/clarity.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ export class CdsIconCustomTag {
static ɵfac: i0.ɵɵFactoryDeclaration<CdsIconCustomTag, never>;
}

// @public (undocumented)
export enum CHANGE_KEYS {
// (undocumented)
FORM = "form",
// (undocumented)
MODEL = "model"
}

// @public (undocumented)
export class ClarityModule {
// (undocumented)
Expand Down Expand Up @@ -4822,7 +4830,7 @@ export const TOGGLE_SERVICE_PROVIDER: {
export function ToggleServiceFactory(): BehaviorSubject<boolean>;

// @public (undocumented)
export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, OnDestroy {
export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, DoCheck, OnDestroy {
constructor(vcr: ViewContainerRef, wrapperType: Type<W>, injector: Injector, ngControl: NgControl, renderer: Renderer2, el: ElementRef);
// (undocumented)
protected controlIdService: ControlIdService;
Expand All @@ -4840,6 +4848,8 @@ export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, OnD
// (undocumented)
protected ngControlService: NgControlService;
// (undocumented)
ngDoCheck(): void;
// (undocumented)
ngOnDestroy(): void;
// (undocumented)
ngOnInit(): void;
Expand Down
69 changes: 66 additions & 3 deletions projects/angular/src/forms/common/wrapped-control.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import { Component, Directive, ElementRef, Injector, NgModule, Renderer2, Type, ViewContainerRef } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { FormsModule, NgControl } from '@angular/forms';
import { FormControl, FormGroup, FormsModule, NgControl, ReactiveFormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';

import { DynamicWrapper } from '../../utils/host-wrapping/dynamic-wrapper';
Expand All @@ -15,7 +15,7 @@ import { ClrHostWrappingModule } from '../../utils/host-wrapping/host-wrapping.m
import { ClrAbstractContainer } from './abstract-container';
import { ClrControlError } from './error';
import { ClrControlHelper } from './helper';
import { IfControlStateService } from './if-control-state/if-control-state.service';
import { CONTROL_STATE, IfControlStateService } from './if-control-state/if-control-state.service';
import { ControlClassService } from './providers/control-class.service';
import { ControlIdService } from './providers/control-id.service';
import { LayoutService } from './providers/layout.service';
Expand Down Expand Up @@ -193,6 +193,45 @@ class WithControlAndSuccess {
model = '';
}

@Component({
template: `
<form-wrapper>
<test-wrapper3>
<label> Label </label>
<textarea testControl3 [formControl]="form.get('control') || form.get('alternative')"></textarea>
<clr-control-success>Successful!</clr-control-success>
</test-wrapper3>
</form-wrapper>
`,
})
class WithDynamicFormControl {
form = new FormGroup<any>({
alternative: new FormControl(),
});

addControl() {
this.form.addControl('control', new FormControl('TEST'));
}
}

@Component({
dtsanevmw marked this conversation as resolved.
Show resolved Hide resolved
dtsanevmw marked this conversation as resolved.
Show resolved Hide resolved
template: `
<form-wrapper>
<test-wrapper3>
<label> Label </label>
<textarea testControl3 [(ngModel)]="form['control']"></textarea>
<clr-control-success>Successful!</clr-control-success>
</test-wrapper3>
</form-wrapper>
`,
})
class WithDynamicNgControl {
form = {};
addControl() {
this.form['control'] = 'TEST';
}
}

interface TestContext {
fixture: ComponentFixture<any>;
wrapper: TestWrapper;
Expand All @@ -210,7 +249,7 @@ export default function (): void {
describe('WrappedFormControl', () => {
function setupTest<T>(testContext: TestContext, testComponent: Type<T>, testControl: any) {
TestBed.configureTestingModule({
imports: [WrappedFormControlTestModule, FormsModule],
imports: [WrappedFormControlTestModule, FormsModule, ReactiveFormsModule],
declarations: [testComponent, ClrControlError, ClrControlHelper, ClrControlSuccess],
});
testContext.fixture = TestBed.createComponent(testComponent);
Expand Down Expand Up @@ -339,6 +378,30 @@ export default function (): void {
});
});

describe('with dynamic controls', function () {
it('with form-control directive', function (this: TestContext) {
setupTest(this, WithDynamicFormControl, TestControl3);
const cb = jasmine.createSpy('cb');
const sub = this.ifControlStateService.statusChanges.subscribe((control: CONTROL_STATE) => cb(control));
expect(cb).toHaveBeenCalledWith(CONTROL_STATE.NONE);
this.fixture.componentInstance.addControl();
this.fixture.detectChanges();
expect(cb).toHaveBeenCalledWith(CONTROL_STATE.VALID);
sub.unsubscribe();
});

it('with ng-control directive', function (this: TestContext) {
dtsanevmw marked this conversation as resolved.
Show resolved Hide resolved
dtsanevmw marked this conversation as resolved.
Show resolved Hide resolved
setupTest(this, WithDynamicNgControl, TestControl3);
const cb = jasmine.createSpy('cb');
const sub = this.ifControlStateService.statusChanges.subscribe((control: CONTROL_STATE) => cb(control));
expect(cb).toHaveBeenCalledWith(CONTROL_STATE.NONE);
this.fixture.componentInstance.addControl();
this.fixture.detectChanges();
expect(cb).toHaveBeenCalledWith(CONTROL_STATE.VALID);
sub.unsubscribe();
});
});

describe('aria roles', function () {
it('adds the aria-describedby for helper', function () {
setupTest(this, WithControlAndHelper, TestControl3);
Expand Down
33 changes: 32 additions & 1 deletion projects/angular/src/forms/common/wrapped-control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@

import {
Directive,
DoCheck,
ElementRef,
HostBinding,
HostListener,
InjectionToken,
Injector,
Input,
KeyValueDiffer,
KeyValueDiffers,
OnDestroy,
OnInit,
Renderer2,
Expand All @@ -31,8 +34,13 @@ import { ControlIdService } from './providers/control-id.service';
import { MarkControlService } from './providers/mark-control.service';
import { Helpers, NgControlService } from './providers/ng-control.service';

export enum CHANGE_KEYS {
FORM = 'form',
MODEL = 'model',
}

@Directive()
export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, OnDestroy {
export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, DoCheck, OnDestroy {
_id: string;

protected renderer: Renderer2;
Expand All @@ -47,6 +55,8 @@ export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, OnD
private markControlService: MarkControlService;
private containerIdService: ContainerIdService;
private _containerInjector: Injector;
private differs: KeyValueDiffers;
private differ: KeyValueDiffer<any, any>;

// I lost way too much time trying to make this work without injecting the ViewContainerRef and the Injector,
// I'm giving up. So we have to inject these two manually for now.
Expand All @@ -66,6 +76,7 @@ export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, OnD
this.ifControlStateService = injector.get(IfControlStateService, null);
this.controlClassService = injector.get(ControlClassService, null);
this.markControlService = injector.get(MarkControlService, null);
this.differs = injector.get(KeyValueDiffers, null);
}

if (this.controlClassService) {
Expand All @@ -86,6 +97,10 @@ export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, OnD
})
);
}

if (ngControl) {
this.differ = this.differs.find(ngControl).create();
}
}

@Input()
Expand Down Expand Up @@ -120,6 +135,22 @@ export class WrappedFormControl<W extends DynamicWrapper> implements OnInit, OnD
}
}

ngDoCheck() {
if (this.differ) {
const changes = this.differ.diff(this.ngControl);
if (changes) {
changes.forEachChangedItem(change => {
if (
(change.key === CHANGE_KEYS.FORM || change.key === CHANGE_KEYS.MODEL) &&
change.currentValue !== change.previousValue
) {
this.triggerValidation();
}
});
}
}
}

ngOnDestroy() {
this.subscriptions.forEach(sub => sub.unsubscribe());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<h1>Dynamic Control Demo</h1>

<p>
We have a State service which have three statuses: NONE, INVALID, VALID. Success and Error messages are shown based on
the value of this state service but if you bind formControl \ ngModel to a control that is currently not available and
then add it dynamically with initial value while marking it as touched and updateValueValidility status change doesn't
trigger and state service value is not updated.
</p>
<br />
<label for="steps"> Steps to test:</label>
<ul id="steps" style="list-style-type: none">
<li>1. Choose scenario two ( text area appears but the control binded to formControl is missing )</li>
<li>2. Choose platform two which is adding the control used in the binding with a initial value.</li>
<li>3. Control should be valid and in success state.</li>
</ul>

<h2>Reactive form</h2>
<form [formGroup]="form">
<clr-select-container>
<label>Choose Platform</label>
<select class="w-60" clrSelect formControlName="platform">
<option value="one">One</option>
<option value="two">Two</option>
</select>
<clr-control-error> Required </clr-control-error>
</clr-select-container>
<clr-radio-container clrInline>
<label>Scenario</label>
<clr-radio-wrapper>
<input type="radio" clrRadio [name]="'scenario'" value="one" formControlName="scenario" />
<label>One</label>
</clr-radio-wrapper>
<clr-radio-wrapper>
<input type="radio" clrRadio [name]="'scenario'" value="two" formControlName="scenario" />
<label>Two</label>
</clr-radio-wrapper>
<clr-control-error> {{ 'REQUIRED' }} </clr-control-error>
</clr-radio-container>
<clr-textarea-container *ngIf="form.get('scenario')?.value === 'two'">
<label>Label</label>
<textarea clrTextarea [formControl]="$any(form).get('control')" required></textarea>
<clr-control-helper>Helper Message</clr-control-helper>
<clr-control-success>Successful</clr-control-success>
<clr-control-error>Required error</clr-control-error>
</clr-textarea-container>
</form>
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.
* This software is released under MIT license.
* The full license information can be found in LICENSE in the root directory of this project.
*/

import { ChangeDetectorRef, Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { Subject } from 'rxjs';
import { filter, takeUntil, tap } from 'rxjs/operators';

@Component({
selector: 'dynamic-controls-demo',
templateUrl: './dynamic-controls.demo.html',
})
export class DynamicControlsDemo {
destroyed = new Subject();
form = new FormGroup<any>({
platform: new FormControl(),
scenario: new FormControl('one'),
});

constructor(private cd: ChangeDetectorRef) {}

ngOnInit() {
this.form
.get('platform')
?.valueChanges.pipe(
filter(value => value === 'two'),
tap(() => {
this.form.addControl('control', new FormControl('test'));
this.form.get('control')?.markAsTouched();
this.form.get('control')?.updateValueAndValidity();
}),
takeUntil(this.destroyed)
)
.subscribe();
}

ngOnDestroy() {
this.destroyed.next();
this.destroyed.complete();
kevinbuhmann marked this conversation as resolved.
Show resolved Hide resolved
}
}
3 changes: 3 additions & 0 deletions projects/demo/src/app/forms/forms.demo.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { FormsRadioDemo } from './controls/radio';
import { FormsSelectDemo } from './controls/select';
import { FormsTextDemo } from './controls/text';
import { FormsTextareaDemo } from './controls/textarea';
import { DynamicControlsDemo } from './dynamic-controls/dynamic-controls.demo';
import { FormsDemo } from './forms.demo';
import { ROUTING } from './forms.demo.routing';
import { FormsGenericContainerDemo } from './generic-container/generic-container';
Expand Down Expand Up @@ -69,6 +70,7 @@ import { FormsValidationDemo } from './validation/validation';
FormsA11yDemo,
FormsGenericContainerDemo,
FormsValidationDemo,
DynamicControlsDemo,
],
exports: [
FormsDemo,
Expand Down Expand Up @@ -97,6 +99,7 @@ import { FormsValidationDemo } from './validation/validation';
FormsA11yDemo,
FormsGenericContainerDemo,
FormsValidationDemo,
DynamicControlsDemo,
],
})
export class FormsDemoModule {}
2 changes: 2 additions & 0 deletions projects/demo/src/app/forms/forms.demo.routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { FormsRadioDemo } from './controls/radio';
import { FormsSelectDemo } from './controls/select';
import { FormsTextDemo } from './controls/text';
import { FormsTextareaDemo } from './controls/textarea';
import { DynamicControlsDemo } from './dynamic-controls/dynamic-controls.demo';
import { FormsDemo } from './forms.demo';
import { FormsGenericContainerDemo } from './generic-container/generic-container';
import { FormsInputGroupDemo } from './input-group/input-group';
Expand Down Expand Up @@ -67,6 +68,7 @@ const ROUTES: Routes = [
{ path: 'a11y', component: FormsA11yDemo },
{ path: 'generic-container', component: FormsGenericContainerDemo },
{ path: 'validation', component: FormsValidationDemo },
{ path: 'dynamic-controls', component: DynamicControlsDemo },
],
},
];
Expand Down
1 change: 1 addition & 0 deletions projects/demo/src/app/forms/forms.demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { Component } from '@angular/core';
<li><a [routerLink]="['./a11y']">a11y</a></li>
<li><a [routerLink]="['./generic-container']">Generic Container</a></li>
<li><a [routerLink]="['./validation']">Validation</a></li>
<li><a [routerLink]="['./dynamic-controls']">Dynamic Controls Reproduction</a></li>
</ul>
<router-outlet></router-outlet>
`,
Expand Down