_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/forms/test/typed_integration_spec.ts_24405_32369 | describe('FormArray', () => {
it('supports inferred arrays', () => {
const c = new FormArray([new FormControl('', {nonNullable: true})]);
{
type ValueType = string[];
let t: ValueType = c.value;
let t1 = c.value;
t1 = null as unknown as ValueType;
}
c.at(0);
c.push(new FormControl('', {nonNullable: true}));
c.insert(0, new FormControl('', {nonNullable: true}));
c.removeAt(0);
c.setControl(0, new FormControl('', {nonNullable: true}));
c.setValue(['', '']);
c.patchValue([]);
c.patchValue(['']);
c.reset();
c.reset([]);
c.reset(['']);
c.clear();
c.valueChanges.subscribe((v) => v);
});
it('supports explicit arrays', () => {
const c = new FormArray<FormControl<string>>([new FormControl('', {nonNullable: true})]);
{
type ValueType = string[];
let t: ValueType = c.value;
let t1 = c.value;
t1 = null as unknown as ValueType;
}
});
it('supports explicit arrays with boolean types', () => {
const c0 = new FormArray([new FormControl(true, {nonNullable: true})]);
const c1: AbstractControl<boolean[]> = new FormArray([
new FormControl(true, {nonNullable: true}),
]);
});
it('supports arrays with the default type', () => {
let c: FormArray;
c = new FormArray([new FormControl('', {nonNullable: true})]);
{
type ValueType = any[];
let t: ValueType = c.value;
let t1 = c.value;
t1 = null as unknown as ValueType;
}
c.at(0);
c.at(0).valueChanges.subscribe((v) => {});
c.push(new FormControl('', {nonNullable: true}));
c.insert(0, new FormControl('', {nonNullable: true}));
c.removeAt(0);
c.setControl(0, new FormControl('', {nonNullable: true}));
c.setValue(['', '']);
c.patchValue([]);
c.patchValue(['']);
c.reset();
c.reset(['']);
c.clear();
});
it('supports empty arrays', () => {
let fa = new FormArray([]);
});
it('supports arrays with nullable controls', () => {
const c = new FormArray([new FormControl<string | null>('')]);
{
type ValueType = Array<string | null>;
let t: ValueType = c.value;
let t1 = c.value;
t1 = null as unknown as ValueType;
}
c.at(0);
c.push(new FormControl<string | null>(null));
c.insert(0, new FormControl<string | null>(null));
c.removeAt(0);
c.setControl(0, new FormControl<string | null>(null));
c.setValue(['', '']);
c.patchValue([]);
c.patchValue(['']);
c.reset();
c.reset([]);
c.reset(['']);
c.clear();
});
it('supports inferred nested arrays', () => {
const c = new FormArray([new FormArray([new FormControl('', {nonNullable: true})])]);
{
type ValueType = Array<Array<string>>;
let t: ValueType = c.value;
let t1 = c.value;
t1 = null as unknown as ValueType;
}
});
it('supports explicit nested arrays', () => {
const c = new FormArray<FormArray<FormControl<string>>>([
new FormArray([new FormControl('', {nonNullable: true})]),
]);
{
type ValueType = Array<Array<string>>;
let t: ValueType = c.value;
let t1 = c.value;
t1 = null as unknown as ValueType;
}
});
it('supports arrays with inferred nested groups', () => {
const fg = new FormGroup({c: new FormControl('', {nonNullable: true})});
const c = new FormArray([fg]);
{
type ValueType = Array<Partial<{c: string}>>;
let t: ValueType = c.value;
let t1 = c.value;
t1 = null as unknown as ValueType;
}
{
type RawValueType = Array<{c: string}>;
let t: RawValueType = c.getRawValue();
let t1 = c.getRawValue();
t1 = null as unknown as RawValueType;
}
});
it('supports arrays with explicit nested groups', () => {
const fg = new FormGroup<{c: FormControl<string>}>({
c: new FormControl('', {nonNullable: true}),
});
const c = new FormArray<FormGroup<{c: FormControl<string>}>>([fg]);
{
type ValueType = Array<Partial<{c: string}>>;
let t: ValueType = c.value;
let t1 = c.value;
t1 = null as unknown as ValueType;
}
{
type RawValueType = Array<{c: string}>;
let t: RawValueType = c.getRawValue();
let t1 = c.getRawValue();
t1 = null as unknown as RawValueType;
}
});
it('should have strongly-typed get', () => {
const c = new FormGroup({
food: new FormArray([new FormControl('2200 Bryant', {nonNullable: true})]),
});
const rv = c.getRawValue();
{
type ValueType = string[];
let t: ValueType = c.get('food')!.value;
let t1 = c.get('food')!.value;
t1 = null as unknown as ValueType;
}
{
type ValueType = string;
let t: ValueType = c.get('food.0')!.value;
let t1 = c.get('food.0')!.value;
t1 = null as unknown as ValueType;
}
});
it('is assignable to UntypedFormArray', () => {
let ufa: UntypedFormArray;
const fa = new FormArray([new FormControl('bob')]);
ufa = fa;
});
});
it('model classes support a complex, deeply nested case', () => {
interface Meal {
entree: FormControl<string>;
dessert: FormControl<string>;
}
const myParty = new FormGroup({
venue: new FormGroup({
location: new FormControl('San Francisco', {nonNullable: true}),
date: new FormGroup({
year: new FormControl(2022, {nonNullable: true}),
month: new FormControl('May', {nonNullable: true}),
day: new FormControl(1, {nonNullable: true}),
}),
}),
dinnerOptions: new FormArray([
new FormGroup({
food: new FormGroup<Meal>({
entree: new FormControl('Baked Tofu', {nonNullable: true}),
dessert: new FormControl('Cheesecake', {nonNullable: true}),
}),
price: new FormGroup({
amount: new FormControl(10, {nonNullable: true}),
currency: new FormControl('USD', {nonNullable: true}),
}),
}),
new FormGroup({
food: new FormGroup<Meal>({
entree: new FormControl('Eggplant Parm', {nonNullable: true}),
dessert: new FormControl('Chocolate Mousse', {nonNullable: true}),
}),
price: new FormGroup({
amount: new FormControl(12, {nonNullable: true}),
currency: new FormControl('USD', {nonNullable: true}),
}),
}),
]),
});
{
type ValueType = Partial<{
venue: Partial<{
location: string;
date: Partial<{
year: number;
month: string;
day: number;
}>;
}>;
dinnerOptions: Partial<{
food: Partial<{
entree: string;
dessert: string;
}>;
price: Partial<{
amount: number;
currency: string;
}>;
}>[];
}>;
let t: ValueType = myParty.value;
let t1 = myParty.value;
t1 = null as unknown as ValueType;
}
{
type RawValueType = {
venue: {
location: string;
date: {
year: number;
month: string;
day: number;
};
};
dinnerOptions: {
food: {
entree: string;
dessert: string;
};
price: {
amount: number;
currency: string;
};
}[];
};
let t: RawValueType = myParty.getRawValue();
let t1 = myParty.getRawValue();
t1 = null as unknown as RawValueType;
}
}); | {
"end_byte": 32369,
"start_byte": 24405,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts"
} |
angular/packages/forms/test/typed_integration_spec.ts_32373_40582 | describe('FormBuilder', () => {
let fb: FormBuilder = new FormBuilder();
beforeEach(() => {
fb = new FormBuilder();
});
describe('should work in basic cases', () => {
it('on FormControls', () => {
const fc = fb.control(42);
expect(fc.value).toEqual(42);
});
it('on FormGroups', () => {
const fc = fb.group({
'foo': 1,
'bar': 2,
});
expect(fc.value.foo).toEqual(1);
});
});
describe('should build FormControls', () => {
it('nullably from values', () => {
const c = fb.control('foo');
{
type RawValueType = string | null;
let t: RawValueType = c.getRawValue();
let t1 = c.getRawValue();
t1 = null as unknown as RawValueType;
}
});
it('non-nullably from values', () => {
const c = fb.control('foo', {nonNullable: true});
{
type RawValueType = string;
let t: RawValueType = c.getRawValue();
let t1 = c.getRawValue();
t1 = null as unknown as RawValueType;
}
});
it('nullably from FormStates', () => {
const c = fb.control({value: 'foo', disabled: false});
{
type RawValueType = string | null;
let t: RawValueType = c.getRawValue();
let t1 = c.getRawValue();
t1 = null as unknown as RawValueType;
}
});
it('non-nullably from FormStates', () => {
const c = fb.control({value: 'foo', disabled: false}, {nonNullable: true});
{
type RawValueType = string;
let t: RawValueType = c.getRawValue();
let t1 = c.getRawValue();
t1 = null as unknown as RawValueType;
}
});
it('with array values', () => {
const c = fb.control([1, 2, 3]);
{
type RawValueType = number[] | null;
let t: RawValueType = c.getRawValue();
let t1 = c.getRawValue();
t1 = null as unknown as RawValueType;
}
});
});
describe('should build FormGroups', () => {
it('from objects with plain values', () => {
const c = fb.group({foo: 'bar'});
{
type ControlsType = {foo: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with optional keys', () => {
const controls = {name: fb.control('')};
const foo: FormGroup<{
name: FormControl<string | null>;
address?: FormControl<string | null>;
}> = fb.group<{name: FormControl<string | null>; address?: FormControl<string | null>}>(
controls,
);
});
it('from objects with FormControlState', () => {
const c = fb.group({foo: {value: 'bar', disabled: false}});
{
type ControlsType = {foo: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with ControlConfigs', () => {
const c = fb.group({foo: ['bar']});
{
type ControlsType = {foo: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with FormControlStates nested inside ControlConfigs', () => {
const c = fb.group({foo: [{value: 'bar', disabled: true}, Validators.required]});
{
type ControlsType = {foo: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with ControlConfigs and validators', () => {
const c = fb.group({foo: ['bar', Validators.required]});
{
type ControlsType = {foo: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
const c2 = fb.group({foo: [[1, 2, 3], Validators.required]});
{
type ControlsType = {foo: FormControl<number[] | null>};
let t: ControlsType = c2.controls;
let t1 = c2.controls;
t1 = null as unknown as ControlsType;
}
expect(c2.controls.foo.value).toEqual([1, 2, 3]);
const c3 = fb.group({foo: [null, Validators.required]});
{
type ControlsType = {foo: FormControl<null>};
let t: ControlsType = c3.controls;
let t1 = c3.controls;
t1 = null as unknown as ControlsType;
}
const c4 = fb.group({foo: [[1, 2, 3], Validators.maxLength(4)]});
{
type ControlsType = {foo: FormControl<number[] | null>};
let t: ControlsType = c4.controls;
let t1 = c4.controls;
t1 = null as unknown as ControlsType;
}
expect(c4.controls.foo.value).toEqual([1, 2, 3]);
});
it('from objects with ControlConfigs and validator lists', () => {
const c = fb.group({foo: ['bar', [Validators.required, Validators.email]]});
{
type ControlsType = {foo: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with ControlConfigs and explicit types', () => {
const c: FormGroup<{foo: FormControl<string | null>}> = fb.group({
foo: ['bar', [Validators.required, Validators.email]],
});
{
type ControlsType = {foo: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
describe('from objects with FormControls', () => {
it('nullably', () => {
const c = fb.group({foo: new FormControl('bar')});
{
type ControlsType = {foo: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('non-nullably', () => {
const c = fb.group({foo: new FormControl('bar', {nonNullable: true})});
{
type ControlsType = {foo: FormControl<string>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with direct FormGroups', () => {
const c = fb.group({foo: new FormGroup({baz: new FormControl('bar')})});
{
type ControlsType = {foo: FormGroup<{baz: FormControl<string | null>}>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with builder FormGroups', () => {
const c = fb.group({foo: fb.group({baz: 'bar'})});
{
type ControlsType = {foo: FormGroup<{baz: FormControl<string | null>}>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with builder FormRecords', () => {
const c = fb.group({foo: fb.record({baz: 'bar'})});
{
type ControlsType = {foo: FormRecord<FormControl<string | null>>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with builder FormArrays', () => {
const c = fb.group({foo: fb.array(['bar'])});
{
type ControlsType = {foo: FormArray<FormControl<string | null>>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
});
}); | {
"end_byte": 40582,
"start_byte": 32373,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts"
} |
angular/packages/forms/test/typed_integration_spec.ts_40588_49574 | describe('should build FormRecords', () => {
it('from objects with plain values', () => {
const c = fb.record({foo: 'bar'});
{
type ControlsType = {[key: string]: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with FormControlState', () => {
const c = fb.record({foo: {value: 'bar', disabled: false}});
{
type ControlsType = {[key: string]: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with ControlConfigs', () => {
const c = fb.record({foo: ['bar']});
{
type ControlsType = {[key: string]: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with ControlConfigs and validators', () => {
const c = fb.record({foo: ['bar', Validators.required]});
{
type ControlsType = {[key: string]: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with ControlConfigs and validator lists', () => {
const c = fb.record({foo: ['bar', [Validators.required, Validators.email]]});
{
type ControlsType = {[key: string]: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with ControlConfigs and explicit types', () => {
const c: FormRecord<FormControl<string | null>> = fb.record({
foo: ['bar', [Validators.required, Validators.email]],
});
{
type ControlsType = {[key: string]: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
describe('from objects with FormControls', () => {
it('nullably', () => {
const c = fb.record({foo: new FormControl('bar')});
{
type ControlsType = {[key: string]: FormControl<string | null>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('non-nullably', () => {
const c = fb.record({foo: new FormControl('bar', {nonNullable: true})});
{
type ControlsType = {[key: string]: FormControl<string>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with builder FormGroups', () => {
const c = fb.record({foo: fb.group({baz: 'bar'})});
{
type ControlsType = {[key: string]: FormGroup<{baz: FormControl<string | null>}>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with builder FormRecords', () => {
const c = fb.record({foo: fb.record({baz: 'bar'})});
{
type ControlsType = {[key: string]: FormRecord<FormControl<string | null>>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from objects with builder FormArrays', () => {
const c = fb.record({foo: fb.array(['bar'])});
{
type ControlsType = {[key: string]: FormArray<FormControl<string | null>>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
});
});
describe('should build FormArrays', () => {
it('from arrays with plain values', () => {
const c = fb.array(['foo']);
{
type ControlsType = Array<FormControl<string | null>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from arrays with FormControlStates', () => {
const c = fb.array([{value: 'foo', disabled: false}]);
{
type ControlsType = Array<FormControl<string | null>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from arrays with ControlConfigs', () => {
const c = fb.array([['foo']]);
{
type ControlsType = Array<FormControl<string | null>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
describe('from arrays with FormControls', () => {
it('nullably', () => {
const c = fb.array([new FormControl('foo')]);
{
type ControlsType = Array<FormControl<string | null>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('non-nullably', () => {
const c = fb.array([new FormControl('foo', {nonNullable: true})]);
{
type ControlsType = Array<FormControl<string>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
});
it('from arrays with direct FormArrays', () => {
const c = fb.array([new FormArray([new FormControl('foo')])]);
{
type ControlsType = Array<FormArray<FormControl<string | null>>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from arrays with builder FormArrays', () => {
const c = fb.array([fb.array(['foo'])]);
{
type ControlsType = Array<FormArray<FormControl<string | null>>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from arrays with builder FormGroups', () => {
const c = fb.array([fb.group({bar: 'foo'})]);
{
type ControlsType = Array<FormGroup<{bar: FormControl<string | null>}>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
it('from arrays with builder FormRecords', () => {
const c = fb.array([fb.record({bar: 'foo'})]);
{
type ControlsType = Array<FormRecord<FormControl<string | null>>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
});
});
it('should work with a complex, deeply nested case', () => {
// Mix a variety of different construction methods and argument types.
const myParty = fb.group({
venue: fb.group({
location: 'San Francisco',
date: fb.group({
year: {value: 2022, disabled: false},
month: fb.control('December', {}),
day: fb.control(new FormControl(14)),
}),
}),
dinnerOptions: fb.array([
fb.group({
food: fb.group({
entree: ['Souffle', Validators.required],
dessert: 'also Souffle',
}),
price: fb.group({
amount: new FormControl(50, {nonNullable: true}),
currency: 'USD',
}),
}),
]),
});
{
type ControlType = {
venue: FormGroup<{
location: FormControl<string | null>;
date: FormGroup<{
year: FormControl<number | null>;
month: FormControl<string | null>;
day: FormControl<number | null>;
}>;
}>;
dinnerOptions: FormArray<
FormGroup<{
food: FormGroup<{
entree: FormControl<string | null>;
dessert: FormControl<string | null>;
}>;
price: FormGroup<{
amount: FormControl<number>;
currency: FormControl<string | null>;
}>;
}>
>;
};
let t: ControlType = myParty.controls;
let d = myParty.controls.dinnerOptions;
let t1 = myParty.controls;
t1 = null as unknown as ControlType;
}
});
}); | {
"end_byte": 49574,
"start_byte": 40588,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts"
} |
angular/packages/forms/test/typed_integration_spec.ts_49578_56358 | describe('NonNullFormBuilder', () => {
let fb: NonNullableFormBuilder;
beforeEach(() => {
fb = new FormBuilder().nonNullable;
});
describe('should build FormControls', () => {
it('non-nullably from values', () => {
const c = fb.control('foo');
{
type RawValueType = string;
let t: RawValueType = c.getRawValue();
let t1 = c.getRawValue();
t1 = null as unknown as RawValueType;
}
c.reset();
expect(c.value).not.toBeNull();
});
});
describe('should build FormGroups', () => {
it('from objects with plain values', () => {
const c = fb.group({foo: 'bar'});
{
type ControlsType = {foo: FormControl<string>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual({foo: 'bar'});
});
it('from objects with FormControlState', () => {
const c = fb.group({foo: {value: 'bar', disabled: false}});
{
type ControlsType = {foo: FormControl<string>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual({foo: 'bar'});
});
it('from objects with ControlConfigs', () => {
const c = fb.group({foo: ['bar']});
{
type ControlsType = {foo: FormControl<string>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual({foo: 'bar'});
});
it('from objects with ControlConfigs and validators', () => {
const c = fb.group({foo: ['bar', Validators.required]});
{
type ControlsType = {foo: FormControl<string>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual({foo: 'bar'});
const c2 = fb.group({foo: [[1, 2, 3], Validators.required]});
{
type ControlsType = {foo: FormControl<number[]>};
let t: ControlsType = c2.controls;
let t1 = c2.controls;
t1 = null as unknown as ControlsType;
}
expect(c2.controls.foo.value).toEqual([1, 2, 3]);
});
it('from objects with ControlConfigs and validator lists', () => {
const c = fb.group({foo: ['bar', [Validators.required, Validators.email]]});
{
type ControlsType = {foo: FormControl<string>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual({foo: 'bar'});
});
it('from objects with ControlConfigs and explicit types', () => {
const c: FormGroup<{foo: FormControl<string>}> = fb.group({
foo: ['bar', [Validators.required, Validators.email]],
});
{
type ControlsType = {foo: FormControl<string>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual({foo: 'bar'});
});
it('without distributing union types', () => {
const c = fb.group({foo: 'bar' as string | number});
{
type ControlsType = {foo: FormControl<string | number>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
let fc = c.controls.foo;
fc = new FormControl<string | number>('', {nonNullable: true});
});
describe('from objects with FormControls', () => {
it('from objects with builder FormGroups', () => {
const c = fb.group({foo: fb.group({baz: 'bar'})});
{
type ControlsType = {foo: FormGroup<{baz: FormControl<string>}>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual({foo: {baz: 'bar'}});
});
it('from objects with builder FormArrays', () => {
const c = fb.group({foo: fb.array(['bar'])});
{
type ControlsType = {foo: FormArray<FormControl<string>>};
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual({foo: ['bar']});
});
});
});
describe('should build FormArrays', () => {
it('from arrays with plain values', () => {
const c = fb.array(['foo']);
{
type ControlsType = Array<FormControl<string>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual(['foo']);
});
it('from arrays with FormControlStates', () => {
const c = fb.array([{value: 'foo', disabled: false}]);
{
type ControlsType = Array<FormControl<string>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual(['foo']);
});
it('from arrays with ControlConfigs', () => {
const c = fb.array([['foo']]);
{
type ControlsType = Array<FormControl<string>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual(['foo']);
});
it('from arrays with builder FormArrays', () => {
const c = fb.array([fb.array(['foo'])]);
{
type ControlsType = Array<FormArray<FormControl<string>>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual([['foo']]);
});
it('from arrays with builder FormGroups', () => {
const c = fb.array([fb.group({bar: 'foo'})]);
{
type ControlsType = Array<FormGroup<{bar: FormControl<string>}>>;
let t: ControlsType = c.controls;
let t1 = c.controls;
t1 = null as unknown as ControlsType;
}
c.reset();
expect(c.value).toEqual([{bar: 'foo'}]);
});
});
});
}); | {
"end_byte": 56358,
"start_byte": 49578,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts"
} |
angular/packages/forms/test/typed_integration_spec.ts_56360_59874 | describe('Untyped Class', () => {
describe('UntypedFormControl', () => {
it('should function like a FormControl with the default type', () => {
const ufc = new UntypedFormControl('foo');
expect(ufc.value).toEqual('foo');
});
it('should default to null with no argument', () => {
const ufc = new UntypedFormControl();
expect(ufc.value).toEqual(null);
});
it('is assignable with the typed version in both directions', () => {
const fc: FormControl<string | null> = new UntypedFormControl('');
const ufc: UntypedFormControl = new FormControl('');
});
it('is an escape hatch from a strongly-typed FormControl', () => {
let fc = new FormControl<number>(42);
const ufc = new UntypedFormControl('foo');
fc = ufc;
});
});
describe('UntypedFormGroup', () => {
it('should function like a FormGroup with the default type', () => {
const ufc = new UntypedFormGroup({foo: new FormControl('bar')});
expect(ufc.value).toEqual({foo: 'bar'});
const fc = ufc.get('foo');
});
it('should allow dotted access to properties', () => {
const ufc = new UntypedFormGroup({foo: new FormControl('bar')});
expect(ufc.value.foo).toEqual('bar');
});
it('should allow access to AbstractControl methods', () => {
const ufc = new UntypedFormGroup({foo: new FormControl('bar')});
expect(ufc.validator).toBe(null);
});
it('is assignable with the typed version in both directions', () => {
const fc: FormGroup<{foo: FormControl<string | null>}> = new UntypedFormGroup({
foo: new UntypedFormControl(''),
});
const ufc: UntypedFormGroup = new FormGroup({foo: new FormControl('')});
});
it('is assignable to FormGroup', () => {
let fg: FormGroup<{foo: FormControl<string | null>}>;
const ufg = new UntypedFormGroup({foo: new FormControl('bar')});
fg = ufg;
});
it('is an escape hatch from a strongly-typed FormGroup', () => {
let fg = new FormGroup({foo: new FormControl<number>(42)});
const ufg = new UntypedFormGroup({foo: new FormControl('bar')});
fg = ufg;
});
});
describe('UntypedFormArray', () => {
it('should function like a FormArray with the default type', () => {
const ufc = new UntypedFormArray([new FormControl('foo')]);
expect(ufc.value).toEqual(['foo']);
ufc.valueChanges.subscribe((v) => v);
});
it('is assignable with the typed version in both directions', () => {
const ufa: UntypedFormArray = new FormArray([new FormControl('')]);
const fa: FormArray<FormControl<string | null>> = new UntypedFormArray([
new UntypedFormControl(''),
]);
});
});
describe('UntypedFormBuilder', () => {
let fb: FormBuilder = new FormBuilder();
let ufb: UntypedFormBuilder = new UntypedFormBuilder();
function typedFn(fb: FormBuilder): void {}
function untypedFn(fb: UntypedFormBuilder): void {}
beforeEach(() => {
ufb = new UntypedFormBuilder();
});
it('should build untyped FormControls', () => {
const ufc = ufb.control(42);
expect(ufc.value).toEqual(42);
});
it('should build untyped FormGroups', () => {
const ufc = ufb.group({
'foo': 1,
'bar': 2,
});
expect(ufc.value.foo).toEqual(1);
});
it('can be provided where a FormBuilder is expected and vice versa', () => {
typedFn(ufb);
untypedFn(fb);
});
});
}); | {
"end_byte": 59874,
"start_byte": 56360,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/typed_integration_spec.ts"
} |
angular/packages/forms/test/form_control_spec.ts_0_5813 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {fakeAsync, tick} from '@angular/core/testing';
import {AsyncValidatorFn, FormArray, FormControl, FormGroup, Validators} from '@angular/forms';
import {asyncValidator, asyncValidatorReturningObservable} from './util';
(function () {
function otherAsyncValidator() {
return Promise.resolve({'other': true});
}
function syncValidator() {
return null;
}
describe('FormControl', () => {
it('should default the value to null', () => {
const c = new FormControl();
expect(c.value).toBe(null);
});
describe('markAllAsTouched', () => {
it('should mark only the control itself as touched', () => {
const control = new FormControl('');
expect(control.touched).toBe(false);
control.markAllAsTouched();
expect(control.touched).toBe(true);
});
});
describe('boxed values', () => {
it('should support valid boxed values on creation', () => {
const c = new FormControl({value: 'some val', disabled: true}, null!, null!);
expect(c.disabled).toBe(true);
expect(c.value).toBe('some val');
expect(c.status).toBe('DISABLED');
});
it('should not treat objects as boxed values when `disabled` field is present, but `value` is missing', () => {
const c = new FormControl({disabled: true});
expect(c.value).toEqual({disabled: true});
expect(c.disabled).toBe(false);
});
it('should honor boxed value with disabled control when validating', () => {
const c = new FormControl({value: '', disabled: true}, Validators.required);
expect(c.disabled).toBe(true);
expect(c.valid).toBe(false);
expect(c.status).toBe('DISABLED');
});
it('should not treat objects as boxed values if they have more than two props', () => {
const c: FormControl = new FormControl(
{value: '', disabled: true, test: 'test'} as any,
null!,
null!,
);
expect(c.value).toEqual({value: '', disabled: true, test: 'test'});
expect(c.disabled).toBe(false);
});
it('should not treat objects as boxed values if disabled is missing', () => {
const c = new FormControl({value: '', test: 'test'}, null!, null!);
expect(c.value).toEqual({value: '', test: 'test'});
expect(c.disabled).toBe(false);
});
});
describe('updateOn', () => {
it('should default to on change', () => {
const c = new FormControl('');
expect(c.updateOn).toEqual('change');
});
it('should default to on change with an options obj', () => {
const c = new FormControl('', {validators: Validators.required});
expect(c.updateOn).toEqual('change');
});
it('should set updateOn when updating on blur', () => {
const c = new FormControl('', {updateOn: 'blur'});
expect(c.updateOn).toEqual('blur');
});
describe('in groups and arrays', () => {
it('should default to group updateOn when not set in control', () => {
const g = new FormGroup(
{one: new FormControl(), two: new FormControl()},
{updateOn: 'blur'},
);
expect(g.get('one')!.updateOn).toEqual('blur');
expect(g.get('two')!.updateOn).toEqual('blur');
});
it('should default to array updateOn when not set in control', () => {
const a = new FormArray([new FormControl(), new FormControl()], {updateOn: 'blur'});
expect(a.get([0])!.updateOn).toEqual('blur');
expect(a.get([1])!.updateOn).toEqual('blur');
});
it('should set updateOn with nested groups', () => {
const g = new FormGroup(
{
group: new FormGroup({one: new FormControl(), two: new FormControl()}),
},
{updateOn: 'blur'},
);
expect(g.get('group.one')!.updateOn).toEqual('blur');
expect(g.get('group.two')!.updateOn).toEqual('blur');
expect(g.get('group')!.updateOn).toEqual('blur');
});
it('should set updateOn with nested arrays', () => {
const g = new FormGroup(
{
arr: new FormArray([new FormControl(), new FormControl()]),
},
{updateOn: 'blur'},
);
expect(g.get(['arr', 0])!.updateOn).toEqual('blur');
expect(g.get(['arr', 1])!.updateOn).toEqual('blur');
expect(g.get('arr')!.updateOn).toEqual('blur');
});
it('should allow control updateOn to override group updateOn', () => {
const g = new FormGroup(
{one: new FormControl('', {updateOn: 'change'}), two: new FormControl()},
{updateOn: 'blur'},
);
expect(g.get('one')!.updateOn).toEqual('change');
expect(g.get('two')!.updateOn).toEqual('blur');
});
it('should set updateOn with complex setup', () => {
const g = new FormGroup({
group: new FormGroup(
{one: new FormControl('', {updateOn: 'change'}), two: new FormControl()},
{updateOn: 'blur'},
),
groupTwo: new FormGroup({one: new FormControl()}, {updateOn: 'submit'}),
three: new FormControl(),
});
expect(g.get('group.one')!.updateOn).toEqual('change');
expect(g.get('group.two')!.updateOn).toEqual('blur');
expect(g.get('groupTwo.one')!.updateOn).toEqual('submit');
expect(g.get('three')!.updateOn).toEqual('change');
});
});
}); | {
"end_byte": 5813,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_control_spec.ts"
} |
angular/packages/forms/test/form_control_spec.ts_5819_14444 | describe('validator', () => {
it('should run validator with the initial value', () => {
const c = new FormControl('value', Validators.required);
expect(c.valid).toEqual(true);
});
it('should rerun the validator when the value changes', () => {
const c = new FormControl('value', Validators.required);
c.setValue(null);
expect(c.valid).toEqual(false);
});
it('should support arrays of validator functions if passed', () => {
const c = new FormControl('value', [Validators.required, Validators.minLength(3)]);
c.setValue('a');
expect(c.valid).toEqual(false);
c.setValue('aaa');
expect(c.valid).toEqual(true);
});
it('should support single validator from options obj', () => {
const c: FormControl = new FormControl(null, {validators: Validators.required});
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({required: true});
c.setValue('value');
expect(c.valid).toEqual(true);
});
it('should support multiple validators from options obj', () => {
const c: FormControl = new FormControl(null, {
validators: [Validators.required, Validators.minLength(3)],
});
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({required: true});
c.setValue('aa');
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({minlength: {requiredLength: 3, actualLength: 2}});
c.setValue('aaa');
expect(c.valid).toEqual(true);
});
it('should support a null validators value', () => {
const c = new FormControl(null, {validators: null});
expect(c.valid).toEqual(true);
});
it('should support an empty options obj', () => {
const c = new FormControl(null, {});
expect(c.valid).toEqual(true);
});
it('should return errors', () => {
const c = new FormControl(null, Validators.required);
expect(c.errors).toEqual({'required': true});
});
it('should set single validator', () => {
const c: FormControl = new FormControl(null);
expect(c.valid).toEqual(true);
c.setValidators(Validators.required);
c.setValue(null);
expect(c.valid).toEqual(false);
c.setValue('abc');
expect(c.valid).toEqual(true);
});
it('should set multiple validators from array', () => {
const c = new FormControl('');
expect(c.valid).toEqual(true);
c.setValidators([Validators.minLength(5), Validators.required]);
c.setValue('');
expect(c.valid).toEqual(false);
c.setValue('abc');
expect(c.valid).toEqual(false);
c.setValue('abcde');
expect(c.valid).toEqual(true);
});
it('should override validators using `setValidators` function', () => {
const c = new FormControl('');
expect(c.valid).toEqual(true);
c.setValidators([Validators.minLength(5), Validators.required]);
c.setValue('');
expect(c.valid).toEqual(false);
c.setValue('abc');
expect(c.valid).toEqual(false);
c.setValue('abcde');
expect(c.valid).toEqual(true);
// Define new set of validators, overriding previously applied ones.
c.setValidators([Validators.maxLength(2)]);
c.setValue('abcdef');
expect(c.valid).toEqual(false);
c.setValue('a');
expect(c.valid).toEqual(true);
});
it('should not mutate the validators array when overriding using setValidators', () => {
const control = new FormControl('');
const originalValidators = [Validators.required];
control.setValidators(originalValidators);
control.addValidators(Validators.minLength(10));
expect(originalValidators.length).toBe(1);
});
it('should override validators by setting `control.validator` field value', () => {
const c = new FormControl('');
expect(c.valid).toEqual(true);
// Define new set of validators, overriding previously applied ones.
c.validator = Validators.compose([Validators.minLength(5), Validators.required]);
c.setValue('');
expect(c.valid).toEqual(false);
c.setValue('abc');
expect(c.valid).toEqual(false);
c.setValue('abcde');
expect(c.valid).toEqual(true);
// Define new set of validators, overriding previously applied ones.
c.validator = Validators.compose([Validators.maxLength(2)]);
c.setValue('abcdef');
expect(c.valid).toEqual(false);
c.setValue('a');
expect(c.valid).toEqual(true);
});
it('should clear validators', () => {
const c = new FormControl('', Validators.required);
expect(c.valid).toEqual(false);
c.clearValidators();
expect(c.validator).toEqual(null);
c.setValue('');
expect(c.valid).toEqual(true);
});
it('should add after clearing', () => {
const c = new FormControl('', Validators.required);
expect(c.valid).toEqual(false);
c.clearValidators();
expect(c.validator).toEqual(null);
c.setValidators([Validators.required]);
expect(c.validator).not.toBe(null);
});
it('should check presence of and remove a validator set in the control constructor', () => {
const c = new FormControl('', Validators.required);
expect(c.hasValidator(Validators.required)).toEqual(true);
c.removeValidators(Validators.required);
expect(c.hasValidator(Validators.required)).toEqual(false);
c.addValidators(Validators.required);
expect(c.hasValidator(Validators.required)).toEqual(true);
});
it('should check presence of and remove a validator set with addValidators', () => {
const c = new FormControl('');
expect(c.hasValidator(Validators.required)).toEqual(false);
c.addValidators(Validators.required);
expect(c.hasValidator(Validators.required)).toEqual(true);
c.removeValidators(Validators.required);
expect(c.hasValidator(Validators.required)).toEqual(false);
});
it('should check presence of and remove multiple validators set at the same time', () => {
const c = new FormControl('3');
const minValidator = Validators.min(4);
c.addValidators([Validators.required, minValidator]);
expect(c.hasValidator(Validators.required)).toEqual(true);
expect(c.hasValidator(minValidator)).toEqual(true);
c.removeValidators([Validators.required, minValidator]);
expect(c.hasValidator(Validators.required)).toEqual(false);
expect(c.hasValidator(minValidator)).toEqual(false);
});
it('should be able to remove a validator added multiple times', () => {
const c = new FormControl('', Validators.required);
c.addValidators(Validators.required);
c.addValidators(Validators.required);
expect(c.hasValidator(Validators.required)).toEqual(true);
c.removeValidators(Validators.required);
expect(c.hasValidator(Validators.required)).toEqual(false);
});
it('should not mutate the validators array when adding/removing sync validators', () => {
const originalValidators = [Validators.required];
const control = new FormControl('', originalValidators);
control.addValidators(Validators.min(10));
expect(originalValidators.length).toBe(1);
control.removeValidators(Validators.required);
expect(originalValidators.length).toBe(1);
});
it('should not mutate the validators array when adding/removing async validators', () => {
const firstValidator = asyncValidator('one');
const secondValidator = asyncValidator('two');
const originalValidators = [firstValidator];
const control = new FormControl('', null, originalValidators);
control.addAsyncValidators(secondValidator);
expect(originalValidators.length).toBe(1);
control.removeAsyncValidators(firstValidator);
expect(originalValidators.length).toBe(1);
});
it('should return false when checking presence of a validator not identical by reference', () => {
const minValidator = Validators.min(5);
const c = new FormControl('1', minValidator);
expect(c.hasValidator(minValidator)).toEqual(true);
expect(c.hasValidator(Validators.min(5))).toEqual(false);
});
}); | {
"end_byte": 14444,
"start_byte": 5819,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_control_spec.ts"
} |
angular/packages/forms/test/form_control_spec.ts_14450_24105 | describe('asyncValidator', () => {
it('should run validator with the initial value', fakeAsync(() => {
const c = new FormControl('value', null!, asyncValidator('expected'));
tick();
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'async': true});
}));
it('should support validators returning observables', fakeAsync(() => {
const c = new FormControl('value', null!, asyncValidatorReturningObservable);
tick();
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'async': true});
}));
it('should rerun the validator when the value changes', fakeAsync(() => {
const c = new FormControl('value', null!, asyncValidator('expected'));
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
}));
it('should run the async validator only when the sync validator passes', fakeAsync(() => {
const c = new FormControl('', Validators.required, asyncValidator('expected'));
tick();
expect(c.errors).toEqual({'required': true});
c.setValue('some value');
tick();
expect(c.errors).toEqual({'async': true});
}));
it('should mark the control as pending while running the async validation', fakeAsync(() => {
const c = new FormControl('', null!, asyncValidator('expected'));
expect(c.pending).toEqual(true);
tick();
expect(c.pending).toEqual(false);
}));
it('should only use the latest async validation run', fakeAsync(() => {
const c = new FormControl(
'',
null!,
asyncValidator('expected', {'long': 200, 'expected': 100}),
);
c.setValue('long');
c.setValue('expected');
tick(300);
expect(c.valid).toEqual(true);
}));
it('should support arrays of async validator functions if passed', fakeAsync(() => {
const c = new FormControl('value', null!, [
asyncValidator('expected'),
otherAsyncValidator,
]);
tick();
expect(c.errors).toEqual({'async': true, 'other': true});
}));
it('should support a single async validator from options obj', fakeAsync(() => {
const c = new FormControl('value', {asyncValidators: asyncValidator('expected')});
expect(c.pending).toEqual(true);
tick();
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'async': true});
}));
it('should support multiple async validators from options obj', fakeAsync(() => {
const c = new FormControl('value', {
asyncValidators: [asyncValidator('expected'), otherAsyncValidator],
});
expect(c.pending).toEqual(true);
tick();
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'async': true, 'other': true});
}));
it('should support a mix of validators from options obj', fakeAsync(() => {
const c = new FormControl('', {
validators: Validators.required,
asyncValidators: asyncValidator('expected'),
});
tick();
expect(c.errors).toEqual({required: true});
c.setValue('value');
expect(c.pending).toBe(true);
tick();
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'async': true});
}));
it('should add single async validator', fakeAsync(() => {
const c = new FormControl('value', null!);
c.setAsyncValidators(asyncValidator('expected'));
expect(c.asyncValidator).not.toEqual(null);
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
}));
it('should add async validator from array', fakeAsync(() => {
const c = new FormControl('value', null!);
c.setAsyncValidators([asyncValidator('expected')]);
expect(c.asyncValidator).not.toEqual(null);
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
}));
it('should override validators using `setAsyncValidators` function', fakeAsync(() => {
const c = new FormControl('');
expect(c.valid).toEqual(true);
c.setAsyncValidators([asyncValidator('expected')]);
c.setValue('');
tick();
expect(c.valid).toEqual(false);
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
// Define new set of validators, overriding previously applied ones.
c.setAsyncValidators([asyncValidator('new expected')]);
c.setValue('expected');
tick();
expect(c.valid).toEqual(false);
c.setValue('new expected');
tick();
expect(c.valid).toEqual(true);
}));
it('should not mutate the validators array when overriding using setValidators', () => {
const control = new FormControl('');
const originalValidators = [asyncValidator('one')];
control.setAsyncValidators(originalValidators);
control.addAsyncValidators(asyncValidator('two'));
expect(originalValidators.length).toBe(1);
});
it('should override validators by setting `control.asyncValidator` field value', fakeAsync(() => {
const c = new FormControl('');
expect(c.valid).toEqual(true);
c.asyncValidator = Validators.composeAsync([asyncValidator('expected')]);
c.setValue('');
tick();
expect(c.valid).toEqual(false);
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
// Define new set of validators, overriding previously applied ones.
c.asyncValidator = Validators.composeAsync([asyncValidator('new expected')]);
c.setValue('expected');
tick();
expect(c.valid).toEqual(false);
c.setValue('new expected');
tick();
expect(c.valid).toEqual(true);
}));
it('should clear async validators', fakeAsync(() => {
const c = new FormControl('value', [asyncValidator('expected'), otherAsyncValidator]);
c.clearValidators();
expect(c.asyncValidator).toEqual(null);
}));
it('should not change validity state if control is disabled while async validating', fakeAsync(() => {
const c = new FormControl('value', [asyncValidator('expected')]);
c.disable();
tick();
expect(c.status).toEqual('DISABLED');
}));
it('should check presence of and remove a validator set in the control constructor', () => {
const asyncVal = asyncValidator('expected');
const c = new FormControl('', null, asyncVal);
expect(c.hasAsyncValidator(asyncVal)).toEqual(true);
c.removeAsyncValidators(asyncVal);
expect(c.hasAsyncValidator(asyncVal)).toEqual(false);
c.addAsyncValidators(asyncVal);
expect(c.hasAsyncValidator(asyncVal)).toEqual(true);
});
it('should check presence of and remove a validator set with addValidators', () => {
const c = new FormControl('');
const asyncVal = asyncValidator('expected');
c.addAsyncValidators(asyncVal);
expect(c.hasAsyncValidator(asyncVal)).toEqual(true);
c.removeAsyncValidators(asyncVal);
expect(c.hasAsyncValidator(asyncVal)).toEqual(false);
});
it('should check presence of and remove multiple validators set at the same time', () => {
const c = new FormControl('3');
const asyncVal1 = asyncValidator('expected1');
const asyncVal2 = asyncValidator('expected2');
c.addAsyncValidators([asyncVal1, asyncVal2]);
expect(c.hasAsyncValidator(asyncVal1)).toEqual(true);
expect(c.hasAsyncValidator(asyncVal2)).toEqual(true);
c.removeAsyncValidators([asyncVal1, asyncVal2]);
expect(c.hasAsyncValidator(asyncVal1)).toEqual(false);
expect(c.hasAsyncValidator(asyncVal2)).toEqual(false);
});
it('should be able to remove a validator added multiple times', () => {
const asyncVal = asyncValidator('expected');
const c = new FormControl('', null, asyncVal);
c.addAsyncValidators(asyncVal);
c.addAsyncValidators(asyncVal);
expect(c.hasAsyncValidator(asyncVal)).toEqual(true);
c.removeAsyncValidators(asyncVal);
expect(c.hasAsyncValidator(asyncVal)).toEqual(false);
});
it('should return false when checking presence of a validator not identical by reference', () => {
const asyncVal = asyncValidator('expected');
const asyncValDifferentFn = asyncValidator('expected');
const c = new FormControl('1', null, asyncVal);
expect(c.hasAsyncValidator(asyncVal)).toEqual(true);
expect(c.hasAsyncValidator(asyncValDifferentFn)).toEqual(false);
});
});
describe('dirty', () => {
it('should be false after creating a control', () => {
const c = new FormControl('value');
expect(c.dirty).toEqual(false);
});
it('should be true after changing the value of the control', () => {
const c = new FormControl('value');
c.markAsDirty();
expect(c.dirty).toEqual(true);
});
});
describe('touched', () => {
it('should be false after creating a control', () => {
const c = new FormControl('value');
expect(c.touched).toEqual(false);
});
it('should be true after markAsTouched runs', () => {
const c = new FormControl('value');
c.markAsTouched();
expect(c.touched).toEqual(true);
});
}); | {
"end_byte": 24105,
"start_byte": 14450,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_control_spec.ts"
} |
angular/packages/forms/test/form_control_spec.ts_24111_28070 | describe('setValue', () => {
let g: FormGroup, c: FormControl;
beforeEach(() => {
c = new FormControl('oldValue');
g = new FormGroup({'one': c});
});
it('should set the value of the control', () => {
c.setValue('newValue');
expect(c.value).toEqual('newValue');
});
it('should invoke ngOnChanges if it is present', () => {
let ngOnChanges: any;
c.registerOnChange((v: any) => (ngOnChanges = ['invoked', v]));
c.setValue('newValue');
expect(ngOnChanges).toEqual(['invoked', 'newValue']);
});
it('should not invoke on change when explicitly specified', () => {
let onChange: any = null;
c.registerOnChange((v: any) => (onChange = ['invoked', v]));
c.setValue('newValue', {emitModelToViewChange: false});
expect(onChange).toBeNull();
});
it('should set the parent', () => {
c.setValue('newValue');
expect(g.value).toEqual({'one': 'newValue'});
});
it('should not set the parent when explicitly specified', () => {
c.setValue('newValue', {onlySelf: true});
expect(g.value).toEqual({'one': 'oldValue'});
});
it('should fire an event', fakeAsync(() => {
c.valueChanges.subscribe((value) => {
expect(value).toEqual('newValue');
});
c.setValue('newValue');
tick();
}));
it('should not fire an event when explicitly specified', fakeAsync(() => {
c.valueChanges.subscribe((value) => {
throw 'Should not happen';
});
c.setValue('newValue', {emitEvent: false});
tick();
}));
it('should work on a disabled control', () => {
g.addControl('two', new FormControl('two'));
c.disable();
c.setValue('new value');
expect(c.value).toEqual('new value');
expect(g.value).toEqual({'two': 'two'});
});
});
describe('patchValue', () => {
let g: FormGroup, c: FormControl;
beforeEach(() => {
c = new FormControl('oldValue');
g = new FormGroup({'one': c});
});
it('should set the value of the control', () => {
c.patchValue('newValue');
expect(c.value).toEqual('newValue');
});
it('should invoke ngOnChanges if it is present', () => {
let ngOnChanges: any;
c.registerOnChange((v: any) => (ngOnChanges = ['invoked', v]));
c.patchValue('newValue');
expect(ngOnChanges).toEqual(['invoked', 'newValue']);
});
it('should not invoke on change when explicitly specified', () => {
let onChange: any = null;
c.registerOnChange((v: any) => (onChange = ['invoked', v]));
c.patchValue('newValue', {emitModelToViewChange: false});
expect(onChange).toBeNull();
});
it('should set the parent', () => {
c.patchValue('newValue');
expect(g.value).toEqual({'one': 'newValue'});
});
it('should not set the parent when explicitly specified', () => {
c.patchValue('newValue', {onlySelf: true});
expect(g.value).toEqual({'one': 'oldValue'});
});
it('should fire an event', fakeAsync(() => {
c.valueChanges.subscribe((value) => {
expect(value).toEqual('newValue');
});
c.patchValue('newValue');
tick();
}));
it('should not fire an event when explicitly specified', fakeAsync(() => {
c.valueChanges.subscribe((value) => {
throw 'Should not happen';
});
c.patchValue('newValue', {emitEvent: false});
tick();
}));
it('should patch value on a disabled control', () => {
g.addControl('two', new FormControl('two'));
c.disable();
c.patchValue('new value');
expect(c.value).toEqual('new value');
expect(g.value).toEqual({'two': 'two'});
});
}); | {
"end_byte": 28070,
"start_byte": 24111,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_control_spec.ts"
} |
angular/packages/forms/test/form_control_spec.ts_28076_35385 | describe('reset()', () => {
let c: FormControl;
beforeEach(() => {
c = new FormControl('initial value');
});
it('should reset to a specific value if passed', () => {
c.setValue('new value');
expect(c.value).toBe('new value');
c.reset('initial value');
expect(c.value).toBe('initial value');
});
it('should not set the parent when explicitly specified', () => {
const g = new FormGroup({'one': c});
c.patchValue('newValue', {onlySelf: true});
expect(g.value).toEqual({'one': 'initial value'});
});
it('should reset to a specific value if passed with boxed value', () => {
c.setValue('new value');
expect(c.value).toBe('new value');
c.reset({value: 'initial value', disabled: false});
expect(c.value).toBe('initial value');
});
it('should clear the control value if no value is passed', () => {
c.setValue('new value');
expect(c.value).toBe('new value');
c.reset();
expect(c.value).toBe(null);
});
it('should reset to the initial value if specified in FormControlOptions', () => {
const c2 = new FormControl('foo', {nonNullable: true});
expect(c2.value).toBe('foo');
expect(c2.defaultValue).toBe('foo');
c2.setValue('bar');
expect(c2.value).toBe('bar');
expect(c2.defaultValue).toBe('foo');
c2.reset();
expect(c2.value).toBe('foo');
expect(c2.defaultValue).toBe('foo');
const c3 = new FormControl('foo', {nonNullable: false});
expect(c3.value).toBe('foo');
expect(c3.defaultValue).toBe(null);
c3.setValue('bar');
expect(c3.value).toBe('bar');
expect(c3.defaultValue).toBe(null);
c3.reset();
expect(c3.value).toBe(null);
expect(c3.defaultValue).toBe(null);
});
it('should look inside FormState objects for a default value', () => {
const c2 = new FormControl({value: 'foo', disabled: false}, {initialValueIsDefault: true});
expect(c2.value).toBe('foo');
expect(c2.defaultValue).toBe('foo');
c2.setValue('bar');
expect(c2.value).toBe('bar');
expect(c2.defaultValue).toBe('foo');
c2.reset();
expect(c2.value).toBe('foo');
expect(c2.defaultValue).toBe('foo');
});
it('should not alter the disabled state when resetting, even if a default value is provided', () => {
const c2 = new FormControl({value: 'foo', disabled: true}, {nonNullable: true});
expect(c2.value).toBe('foo');
expect(c2.defaultValue).toBe('foo');
expect(c2.disabled).toBe(true);
c2.setValue('bar');
c2.enable();
c2.reset();
expect(c2.value).toBe('foo');
expect(c2.defaultValue).toBe('foo');
expect(c2.disabled).toBe(false);
});
it('should update the value of any parent controls with passed value', () => {
const g = new FormGroup({'one': c});
c.setValue('new value');
expect(g.value).toEqual({'one': 'new value'});
c.reset('initial value');
expect(g.value).toEqual({'one': 'initial value'});
});
it('should update the value of any parent controls with null value', () => {
const g = new FormGroup({'one': c});
c.setValue('new value');
expect(g.value).toEqual({'one': 'new value'});
c.reset();
expect(g.value).toEqual({'one': null});
});
it('should mark the control as pristine', () => {
c.markAsDirty();
expect(c.pristine).toBe(false);
c.reset();
expect(c.pristine).toBe(true);
});
it('should set the parent pristine state if all pristine', () => {
const g = new FormGroup({'one': c});
c.markAsDirty();
expect(g.pristine).toBe(false);
c.reset();
expect(g.pristine).toBe(true);
});
it('should not set the parent pristine state if it has other dirty controls', () => {
const c2 = new FormControl('two');
const g = new FormGroup({'one': c, 'two': c2});
c.markAsDirty();
c2.markAsDirty();
c.reset();
expect(g.pristine).toBe(false);
});
it('should mark the control as untouched', () => {
c.markAsTouched();
expect(c.untouched).toBe(false);
c.reset();
expect(c.untouched).toBe(true);
});
it('should set the parent untouched state if all untouched', () => {
const g = new FormGroup({'one': c});
c.markAsTouched();
expect(g.untouched).toBe(false);
c.reset();
expect(g.untouched).toBe(true);
});
it('should not set the parent untouched state if other touched controls', () => {
const c2 = new FormControl('two');
const g = new FormGroup({'one': c, 'two': c2});
c.markAsTouched();
c2.markAsTouched();
c.reset();
expect(g.untouched).toBe(false);
});
it('should retain the disabled state of the control', () => {
c.disable();
c.reset();
expect(c.disabled).toBe(true);
});
it('should set disabled state based on boxed value if passed', () => {
c.disable();
c.reset({value: null, disabled: false});
expect(c.disabled).toBe(false);
});
describe('reset() events', () => {
let g: FormGroup, c2: FormControl, logger: any[];
beforeEach(() => {
c2 = new FormControl('two');
g = new FormGroup({'one': c, 'two': c2});
logger = [];
});
it('should emit one valueChange event per reset control', () => {
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
c.reset();
expect(logger).toEqual(['control1', 'group']);
});
it('should not fire an event when explicitly specified', fakeAsync(() => {
g.valueChanges.subscribe((value) => {
throw 'Should not happen';
});
c.valueChanges.subscribe((value) => {
throw 'Should not happen';
});
c2.valueChanges.subscribe((value) => {
throw 'Should not happen';
});
c.reset(null, {emitEvent: false});
tick();
}));
it('should emit one statusChange event per reset control', () => {
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
c.reset();
expect(logger).toEqual(['control1', 'group']);
});
it('should emit one statusChange event per disabled control', () => {
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
c.reset({value: null, disabled: true});
expect(logger).toEqual(['control1', 'group']);
});
});
}); | {
"end_byte": 35385,
"start_byte": 28076,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_control_spec.ts"
} |
angular/packages/forms/test/form_control_spec.ts_35391_39850 | describe('valueChanges & statusChanges', () => {
let c: FormControl;
beforeEach(() => {
c = new FormControl('old', Validators.required);
});
it('should fire an event after the value has been updated', (done) => {
c.valueChanges.subscribe({
next: (value: any) => {
expect(c.value).toEqual('new');
expect(value).toEqual('new');
done();
},
});
c.setValue('new');
});
it('should fire an event after the status has been updated to invalid', fakeAsync(() => {
c.statusChanges.subscribe({
next: (status: any) => {
expect(c.status).toEqual('INVALID');
expect(status).toEqual('INVALID');
},
});
c.setValue('');
tick();
}));
it('should fire statusChanges events for async validators added via options object', fakeAsync(() => {
// The behavior can be tested for each of the model types.
let statuses: string[] = [];
// Create a form control with an async validator added via options object.
const asc = new FormControl('', {asyncValidators: [() => Promise.resolve(null)]});
// Subscribe to status changes.
asc.statusChanges.subscribe((status: any) => statuses.push(status));
// After a tick, the async validator should change status PENDING -> VALID.
tick();
expect(statuses).toEqual(['VALID']);
}));
it('should fire an event after the status has been updated to pending', fakeAsync(() => {
const c = new FormControl('old', Validators.required, asyncValidator('expected'));
const log: string[] = [];
c.valueChanges.subscribe({next: (value: any) => log.push(`value: '${value}'`)});
c.statusChanges.subscribe({next: (status: any) => log.push(`status: '${status}'`)});
c.setValue('');
tick();
c.setValue('nonEmpty');
tick();
c.setValue('expected');
tick();
expect(log).toEqual([
"value: ''",
"status: 'INVALID'",
"value: 'nonEmpty'",
"status: 'PENDING'",
"status: 'INVALID'",
"value: 'expected'",
"status: 'PENDING'",
"status: 'VALID'",
]);
}));
it('should update set errors and status before emitting an event', fakeAsync(() => {
c.setValue('');
tick();
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'required': true});
}));
it('should return a cold observable', fakeAsync(() => {
let value: string | null = null;
c.setValue('will be ignored');
c.valueChanges.subscribe((v) => (value = v));
c.setValue('new');
tick();
// @ts-expect-error see microsoft/TypeScript#9998
expect(value).toEqual('new');
}));
});
describe('setErrors', () => {
it('should set errors on a control', () => {
const c = new FormControl('someValue');
c.setErrors({'someError': true});
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'someError': true});
});
it('should reset the errors and validity when the value changes', () => {
const c = new FormControl('someValue', Validators.required);
c.setErrors({'someError': true});
c.setValue('');
expect(c.errors).toEqual({'required': true});
});
it("should update the parent group's validity", () => {
const c = new FormControl('someValue');
const g = new FormGroup({'one': c});
expect(g.valid).toEqual(true);
c.setErrors({'someError': true});
expect(g.valid).toEqual(false);
});
it("should not reset parent's errors", () => {
const c = new FormControl('someValue');
const g = new FormGroup({'one': c});
g.setErrors({'someGroupError': true});
c.setErrors({'someError': true});
expect(g.errors).toEqual({'someGroupError': true});
});
it('should reset errors when updating a value', () => {
const c = new FormControl('oldValue');
const g = new FormGroup({'one': c});
g.setErrors({'someGroupError': true});
c.setErrors({'someError': true});
c.setValue('newValue');
expect(c.errors).toEqual(null);
expect(g.errors).toEqual(null);
});
}); | {
"end_byte": 39850,
"start_byte": 35391,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_control_spec.ts"
} |
angular/packages/forms/test/form_control_spec.ts_39856_47864 | describe('disable() & enable()', () => {
it('should mark the control as disabled', () => {
const c = new FormControl(null);
expect(c.disabled).toBe(false);
expect(c.valid).toBe(true);
c.disable();
expect(c.disabled).toBe(true);
expect(c.valid).toBe(false);
c.enable();
expect(c.disabled).toBe(false);
expect(c.valid).toBe(true);
});
it('should set the control status as disabled', () => {
const c = new FormControl(null);
expect(c.status).toEqual('VALID');
c.disable();
expect(c.status).toEqual('DISABLED');
c.enable();
expect(c.status).toEqual('VALID');
});
it('should retain the original value when disabled', () => {
const c = new FormControl('some value');
expect(c.value).toEqual('some value');
c.disable();
expect(c.value).toEqual('some value');
c.enable();
expect(c.value).toEqual('some value');
});
it('should keep the disabled control in the group, but return false for contains()', () => {
const c = new FormControl('');
const g = new FormGroup({'one': c});
expect(g.get('one')).toBeDefined();
expect(g.contains('one')).toBe(true);
c.disable();
expect(g.get('one')).toBeDefined();
expect(g.contains('one')).toBe(false);
});
it('should mark the parent group disabled if all controls are disabled', () => {
const c = new FormControl();
const c2 = new FormControl();
const g = new FormGroup({'one': c, 'two': c2});
expect(g.enabled).toBe(true);
c.disable();
expect(g.enabled).toBe(true);
c2.disable();
expect(g.enabled).toBe(false);
c.enable();
expect(g.enabled).toBe(true);
});
it('should update the parent group value when child control status changes', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const g = new FormGroup({'one': c, 'two': c2});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
c.disable();
expect(g.value).toEqual({'two': 'two'});
c2.disable();
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
c.enable();
expect(g.value).toEqual({'one': 'one'});
});
it('should mark the parent array disabled if all controls are disabled', () => {
const c = new FormControl();
const c2 = new FormControl();
const a = new FormArray([c, c2]);
expect(a.enabled).toBe(true);
c.disable();
expect(a.enabled).toBe(true);
c2.disable();
expect(a.enabled).toBe(false);
c.enable();
expect(a.enabled).toBe(true);
});
it('should update the parent array value when child control status changes', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const a = new FormArray([c, c2]);
expect(a.value).toEqual(['one', 'two']);
c.disable();
expect(a.value).toEqual(['two']);
c2.disable();
expect(a.value).toEqual(['one', 'two']);
c.enable();
expect(a.value).toEqual(['one']);
});
it('should ignore disabled array controls when determining dirtiness', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const a = new FormArray([c, c2]);
c.markAsDirty();
expect(a.dirty).toBe(true);
c.disable();
expect(c.dirty).toBe(true);
expect(a.dirty).toBe(false);
c.enable();
expect(a.dirty).toBe(true);
});
it('should not make a dirty array not dirty when disabling controls', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const a = new FormArray([c, c2]);
a.markAsDirty();
expect(a.dirty).toBe(true);
expect(c.dirty).toBe(false);
c.disable();
expect(a.dirty).toBe(true);
c.enable();
expect(a.dirty).toBe(true);
});
it('should ignore disabled controls in validation', () => {
const c = new FormControl(null, Validators.required);
const c2 = new FormControl(null);
const g = new FormGroup({one: c, two: c2});
expect(g.valid).toBe(false);
c.disable();
expect(g.valid).toBe(true);
c.enable();
expect(g.valid).toBe(false);
});
it('should ignore disabled controls when serializing value in a group', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const g = new FormGroup({one: c, two: c2});
expect(g.value).toEqual({one: 'one', two: 'two'});
c.disable();
expect(g.value).toEqual({two: 'two'});
c.enable();
expect(g.value).toEqual({one: 'one', two: 'two'});
});
it('should ignore disabled controls when serializing value in an array', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const a = new FormArray([c, c2]);
expect(a.value).toEqual(['one', 'two']);
c.disable();
expect(a.value).toEqual(['two']);
c.enable();
expect(a.value).toEqual(['one', 'two']);
});
it('should ignore disabled controls when determining dirtiness', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const g = new FormGroup({one: c, two: c2});
c.markAsDirty();
expect(g.dirty).toBe(true);
c.disable();
expect(c.dirty).toBe(true);
expect(g.dirty).toBe(false);
c.enable();
expect(g.dirty).toBe(true);
});
it('should not make a dirty group not dirty when disabling controls', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const g = new FormGroup({one: c, two: c2});
g.markAsDirty();
expect(g.dirty).toBe(true);
expect(c.dirty).toBe(false);
c.disable();
expect(g.dirty).toBe(true);
c.enable();
expect(g.dirty).toBe(true);
});
it('should ignore disabled controls when determining touched state', () => {
const c = new FormControl('one');
const c2 = new FormControl('two');
const g = new FormGroup({one: c, two: c2});
c.markAsTouched();
expect(g.touched).toBe(true);
c.disable();
expect(c.touched).toBe(true);
expect(g.touched).toBe(false);
c.enable();
expect(g.touched).toBe(true);
});
it('should not run validators on disabled controls', () => {
const validator = jasmine.createSpy('validator');
const c = new FormControl('', validator);
expect(validator.calls.count()).toEqual(1);
c.disable();
expect(validator.calls.count()).toEqual(1);
c.setValue('value');
expect(validator.calls.count()).toEqual(1);
c.enable();
expect(validator.calls.count()).toEqual(2);
});
describe('disabled errors', () => {
it('should clear out the errors when disabled', () => {
const c = new FormControl('', Validators.required);
expect(c.errors).toEqual({required: true});
c.disable();
expect(c.errors).toEqual(null);
c.enable();
expect(c.errors).toEqual({required: true});
});
it('should clear out async errors when disabled', fakeAsync(() => {
const c = new FormControl('', null!, asyncValidator('expected'));
tick();
expect(c.errors).toEqual({'async': true});
c.disable();
expect(c.errors).toEqual(null);
c.enable();
tick();
expect(c.errors).toEqual({'async': true});
}));
}); | {
"end_byte": 47864,
"start_byte": 39856,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_control_spec.ts"
} |
angular/packages/forms/test/form_control_spec.ts_47872_53214 | describe('disabled events', () => {
let logger: string[];
let c: FormControl;
let g: FormGroup;
beforeEach(() => {
logger = [];
c = new FormControl('', Validators.required);
g = new FormGroup({one: c});
});
it('should emit a statusChange event when disabled status changes', () => {
c.statusChanges.subscribe((status: string) => logger.push(status));
c.disable();
expect(logger).toEqual(['DISABLED']);
c.enable();
expect(logger).toEqual(['DISABLED', 'INVALID']);
});
it('should emit status change events in correct order', () => {
c.statusChanges.subscribe(() => logger.push('control'));
g.statusChanges.subscribe(() => logger.push('group'));
c.disable();
expect(logger).toEqual(['control', 'group']);
});
it('should throw when sync validator passed into async validator param', () => {
const fn = () =>
new FormControl('', syncValidator, syncValidator as unknown as AsyncValidatorFn);
// test for the specific error since without the error check it would still throw an error
// but
// not a meaningful one
expect(fn).toThrowError(
'NG01101: Expected async validator to return Promise or Observable. ' +
'Are you using a synchronous validator where an async validator is expected? ' +
'Find more at https://angular.dev/errors/NG01101',
);
});
it('should not emit value change events when emitEvent = false', () => {
c.valueChanges.subscribe(() => logger.push('control'));
g.valueChanges.subscribe(() => logger.push('group'));
c.disable({emitEvent: false});
expect(logger).toEqual([]);
c.enable({emitEvent: false});
expect(logger).toEqual([]);
});
it('should not emit status change events when emitEvent = false', () => {
c.statusChanges.subscribe(() => logger.push('control'));
g.statusChanges.subscribe(() => logger.push('form'));
c.disable({emitEvent: false});
expect(logger).toEqual([]);
c.enable({emitEvent: false});
expect(logger).toEqual([]);
});
});
});
describe('pending', () => {
let c: FormControl;
beforeEach(() => {
c = new FormControl('value');
});
it('should be false after creating a control', () => {
expect(c.pending).toEqual(false);
});
it('should be true after changing the value of the control', () => {
c.markAsPending();
expect(c.pending).toEqual(true);
});
describe('status change events', () => {
let logger: string[];
beforeEach(() => {
logger = [];
c.statusChanges.subscribe((status) => logger.push(status));
});
it('should emit event after marking control as pending', () => {
c.markAsPending();
expect(logger).toEqual(['PENDING']);
});
it('should not emit event when emitEvent = false', () => {
c.markAsPending({emitEvent: false});
expect(logger).toEqual([]);
});
});
});
describe('can be extended', () => {
// We don't technically support extending Forms classes, but people do it anyway.
// We need to make sure that there is some way to extend them to avoid causing breakage.
class FCExt extends FormControl {
constructor(
formState?:
| any
| {
value?: any;
disabled?: boolean;
},
...args: any
) {
super(formState, ...args);
}
}
it('should perform basic FormControl operations', () => {
const nc = new FCExt({value: 'foo'});
nc.setValue('bar');
// There is no need to assert because, if this test compiles, then it is possible to correctly
// extend FormControl.
});
});
describe('inspecting the prototype still provides FormControl type', () => {
// The constructor should be a function with a prototype property of T.
// (This is the assumption we don't want to break.)
type Constructor<T> = Function & {prototype: T};
function isInstanceOf<T>(value: Constructor<T>, arg: unknown): arg is T {
// The implementation does not matter; we want to check whether this guard narrows the type.
return true;
}
// This is a nullable FormControl, and we want isInstanceOf to narrow the type.
const fcOrNull: FormControl | null = new FormControl(42);
it('and is appropriately narrowed', () => {
if (isInstanceOf(FormControl, fcOrNull)) {
// If the guard does not work, then this code will not compile due to null being in the
// type.
fcOrNull.setValue(7);
}
});
});
describe('Function.name', () => {
it('returns FormControl', () => {
// This is always true in the trivial case, but can be broken by various methods of overriding
// FormControl's exported constructor.
expect(FormControl.name).toBe('FormControl');
});
});
});
})(); | {
"end_byte": 53214,
"start_byte": 47872,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_control_spec.ts"
} |
angular/packages/forms/test/validators_spec.ts_0_8014 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {fakeAsync, tick} from '@angular/core/testing';
import {
AbstractControl,
AsyncValidator,
AsyncValidatorFn,
FormArray,
FormControl,
ValidationErrors,
ValidatorFn,
Validators,
} from '@angular/forms';
import {Observable, of, timer} from 'rxjs';
import {first, map} from 'rxjs/operators';
import {normalizeValidators} from '../src/validators';
(function () {
function validator(key: string, error: any): ValidatorFn {
return (c: AbstractControl) => {
const r: ValidationErrors = {};
r[key] = error;
return r;
};
}
class AsyncValidatorDirective implements AsyncValidator {
constructor(
private expected: string,
private error: any,
) {}
validate(c: any): Observable<ValidationErrors> {
return new Observable((obs: any) => {
const error = this.expected !== c.value ? this.error : null;
obs.next(error);
obs.complete();
});
}
}
describe('Validators', () => {
describe('min', () => {
it('should not error on an empty string', () => {
expect(Validators.min(2)(new FormControl(''))).toBeNull();
});
it('should not error on null', () => {
expect(Validators.min(2)(new FormControl(null))).toBeNull();
});
it('should not error on undefined', () => {
expect(Validators.min(2)(new FormControl(undefined))).toBeNull();
});
it('should return null if NaN after parsing', () => {
expect(Validators.min(2)(new FormControl('a'))).toBeNull();
});
it('should return a validation error on small values', () => {
expect(Validators.min(2)(new FormControl(1))).toEqual({'min': {'min': 2, 'actual': 1}});
});
it('should return a validation error on small values converted from strings', () => {
expect(Validators.min(2)(new FormControl('1'))).toEqual({'min': {'min': 2, 'actual': '1'}});
});
it('should not error on small float number validation', () => {
expect(Validators.min(1.2)(new FormControl(1.25))).toBeNull();
});
it('should not error on equal float values', () => {
expect(Validators.min(1.25)(new FormControl(1.25))).toBeNull();
});
it('should return a validation error on big values', () => {
expect(Validators.min(1.25)(new FormControl(1.2))).toEqual({
'min': {'min': 1.25, 'actual': 1.2},
});
});
it('should not error on big values', () => {
expect(Validators.min(2)(new FormControl(3))).toBeNull();
});
it('should not error on equal values', () => {
expect(Validators.min(2)(new FormControl(2))).toBeNull();
});
it('should not error on equal values when value is string', () => {
expect(Validators.min(2)(new FormControl('2'))).toBeNull();
});
it('should validate as expected when min value is a string', () => {
expect(Validators.min('2' as any)(new FormControl(1))).toEqual({
'min': {'min': '2', 'actual': 1},
});
});
it('should return null if min value is undefined', () => {
expect(Validators.min(undefined as any)(new FormControl(3))).toBeNull();
});
it('should return null if min value is null', () => {
expect(Validators.min(null as any)(new FormControl(3))).toBeNull();
});
});
describe('max', () => {
it('should not error on an empty string', () => {
expect(Validators.max(2)(new FormControl(''))).toBeNull();
});
it('should not error on null', () => {
expect(Validators.max(2)(new FormControl(null))).toBeNull();
});
it('should not error on undefined', () => {
expect(Validators.max(2)(new FormControl(undefined))).toBeNull();
});
it('should return null if NaN after parsing', () => {
expect(Validators.max(2)(new FormControl('aaa'))).toBeNull();
});
it('should not error on small float number validation', () => {
expect(Validators.max(1.2)(new FormControl(1.15))).toBeNull();
});
it('should not error on equal float values', () => {
expect(Validators.max(1.25)(new FormControl(1.25))).toBeNull();
});
it('should return a validation error on big values', () => {
expect(Validators.max(1.25)(new FormControl(1.3))).toEqual({
'max': {'max': 1.25, 'actual': 1.3},
});
});
it('should return a validation error on big values', () => {
expect(Validators.max(2)(new FormControl(3))).toEqual({'max': {'max': 2, 'actual': 3}});
});
it('should return a validation error on big values converted from strings', () => {
expect(Validators.max(2)(new FormControl('3'))).toEqual({'max': {'max': 2, 'actual': '3'}});
});
it('should not error on small values', () => {
expect(Validators.max(2)(new FormControl(1))).toBeNull();
});
it('should not error on equal values', () => {
expect(Validators.max(2)(new FormControl(2))).toBeNull();
});
it('should not error on equal values when value is string', () => {
expect(Validators.max(2)(new FormControl('2'))).toBeNull();
});
it('should validate as expected when max value is a string', () => {
expect(Validators.max('2' as any)(new FormControl(3))).toEqual({
'max': {'max': '2', 'actual': 3},
});
});
it('should return null if max value is undefined', () => {
expect(Validators.max(undefined as any)(new FormControl(3))).toBeNull();
});
it('should return null if max value is null', () => {
expect(Validators.max(null as any)(new FormControl(3))).toBeNull();
});
});
describe('required', () => {
it('should error on an empty string', () => {
expect(Validators.required(new FormControl(''))).toEqual({'required': true});
});
it('should error on null', () => {
expect(Validators.required(new FormControl(null))).toEqual({'required': true});
});
it('should not error on undefined', () => {
expect(Validators.required(new FormControl(undefined))).toEqual({'required': true});
});
it('should not error on a non-empty string', () => {
expect(Validators.required(new FormControl('not empty'))).toBeNull();
});
it('should accept zero as valid', () => {
expect(Validators.required(new FormControl(0))).toBeNull();
});
it('should error on an empty array', () =>
expect(Validators.required(new FormControl([]))).toEqual({'required': true}));
it('should not error on a non-empty array', () =>
expect(Validators.required(new FormControl([1, 2]))).toBeNull());
it('should not error on an object containing a length attribute that is zero', () => {
expect(Validators.required(new FormControl({id: 1, length: 0, width: 0}))).toBeNull();
});
});
describe('requiredTrue', () => {
it('should error on false', () =>
expect(Validators.requiredTrue(new FormControl(false))).toEqual({'required': true}));
it('should not error on true', () =>
expect(Validators.requiredTrue(new FormControl(true))).toBeNull());
});
describe('email', () => {
it('should not error on an empty string', () =>
expect(Validators.email(new FormControl(''))).toBeNull());
it('should not error on null', () =>
expect(Validators.email(new FormControl(null))).toBeNull());
it('should error on invalid email', () =>
expect(Validators.email(new FormControl('some text'))).toEqual({'email': true}));
it('should not error on valid email', () =>
expect(Validators.email(new FormControl('test@gmail.com'))).toBeNull());
}); | {
"end_byte": 8014,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/validators_spec.ts"
} |
angular/packages/forms/test/validators_spec.ts_8020_16077 | describe('minLength', () => {
it('should not error on an empty string', () => {
expect(Validators.minLength(2)(new FormControl(''))).toBeNull();
});
it('should not error on null', () => {
expect(Validators.minLength(2)(new FormControl(null))).toBeNull();
});
it('should not error on undefined', () => {
expect(Validators.minLength(2)(new FormControl(undefined))).toBeNull();
});
it('should not error on valid strings', () => {
expect(Validators.minLength(2)(new FormControl('aa'))).toBeNull();
});
it('should error on short strings', () => {
expect(Validators.minLength(2)(new FormControl('a'))).toEqual({
'minlength': {'requiredLength': 2, 'actualLength': 1},
});
});
it('should not error when FormArray has valid length', () => {
const fa = new FormArray([new FormControl(''), new FormControl('')]);
expect(Validators.minLength(2)(fa)).toBeNull();
});
it('should error when FormArray has invalid length', () => {
const fa = new FormArray([new FormControl('')]);
expect(Validators.minLength(2)(fa)).toEqual({
'minlength': {'requiredLength': 2, 'actualLength': 1},
});
});
it('should always return null with numeric values', () => {
expect(Validators.minLength(1)(new FormControl(0))).toBeNull();
expect(Validators.minLength(1)(new FormControl(1))).toBeNull();
expect(Validators.minLength(1)(new FormControl(-1))).toBeNull();
expect(Validators.minLength(1)(new FormControl(+1))).toBeNull();
});
it('should trigger validation for an object that contains numeric length property', () => {
const value = {length: 5, someValue: [1, 2, 3, 4, 5]};
expect(Validators.minLength(1)(new FormControl(value))).toBeNull();
expect(Validators.minLength(10)(new FormControl(value))).toEqual({
'minlength': {'requiredLength': 10, 'actualLength': 5},
});
});
it('should return null when passing a boolean', () => {
expect(Validators.minLength(1)(new FormControl(true))).toBeNull();
expect(Validators.minLength(1)(new FormControl(false))).toBeNull();
});
});
describe('maxLength', () => {
it('should not error on an empty string', () => {
expect(Validators.maxLength(2)(new FormControl(''))).toBeNull();
});
it('should not error on null', () => {
expect(Validators.maxLength(2)(new FormControl(null))).toBeNull();
});
it('should not error on undefined', () => {
expect(Validators.maxLength(2)(new FormControl(undefined))).toBeNull();
});
it('should not error on valid strings', () => {
expect(Validators.maxLength(2)(new FormControl('aa'))).toBeNull();
});
it('should error on long strings', () => {
expect(Validators.maxLength(2)(new FormControl('aaa'))).toEqual({
'maxlength': {'requiredLength': 2, 'actualLength': 3},
});
});
it('should not error when FormArray has valid length', () => {
const fa = new FormArray([new FormControl(''), new FormControl('')]);
expect(Validators.maxLength(2)(fa)).toBeNull();
});
it('should error when FormArray has invalid length', () => {
const fa = new FormArray([new FormControl(''), new FormControl('')]);
expect(Validators.maxLength(1)(fa)).toEqual({
'maxlength': {'requiredLength': 1, 'actualLength': 2},
});
});
it('should always return null with numeric values', () => {
expect(Validators.maxLength(1)(new FormControl(0))).toBeNull();
expect(Validators.maxLength(1)(new FormControl(1))).toBeNull();
expect(Validators.maxLength(1)(new FormControl(-1))).toBeNull();
expect(Validators.maxLength(1)(new FormControl(+1))).toBeNull();
});
it('should trigger validation for an object that contains numeric length property', () => {
const value = {length: 5, someValue: [1, 2, 3, 4, 5]};
expect(Validators.maxLength(10)(new FormControl(value))).toBeNull();
expect(Validators.maxLength(1)(new FormControl(value))).toEqual({
'maxlength': {'requiredLength': 1, 'actualLength': 5},
});
});
it('should return null when passing a boolean', () => {
expect(Validators.maxLength(1)(new FormControl(true))).toBeNull();
expect(Validators.maxLength(1)(new FormControl(false))).toBeNull();
});
});
describe('pattern', () => {
it('should not error on an empty string', () => {
expect(Validators.pattern('[a-zA-Z ]+')(new FormControl(''))).toBeNull();
});
it('should not error on null', () => {
expect(Validators.pattern('[a-zA-Z ]+')(new FormControl(null))).toBeNull();
});
it('should not error on undefined', () => {
expect(Validators.pattern('[a-zA-Z ]+')(new FormControl(undefined))).toBeNull();
});
it('should not error on null value and "null" pattern', () => {
expect(Validators.pattern('null')(new FormControl(null))).toBeNull();
});
it('should not error on valid strings', () =>
expect(Validators.pattern('[a-zA-Z ]*')(new FormControl('aaAA'))).toBeNull());
it('should error on failure to match string', () => {
expect(Validators.pattern('[a-zA-Z ]*')(new FormControl('aaa0'))).toEqual({
'pattern': {'requiredPattern': '^[a-zA-Z ]*$', 'actualValue': 'aaa0'},
});
});
it('should accept RegExp object', () => {
const pattern: RegExp = new RegExp('[a-zA-Z ]+');
expect(Validators.pattern(pattern)(new FormControl('aaAA'))).toBeNull();
});
it('should error on failure to match RegExp object', () => {
const pattern: RegExp = new RegExp('^[a-zA-Z ]*$');
expect(Validators.pattern(pattern)(new FormControl('aaa0'))).toEqual({
'pattern': {'requiredPattern': '/^[a-zA-Z ]*$/', 'actualValue': 'aaa0'},
});
});
it('should not error on "null" pattern', () =>
expect(Validators.pattern(null!)(new FormControl('aaAA'))).toBeNull());
it('should not error on "undefined" pattern', () =>
expect(Validators.pattern(undefined!)(new FormControl('aaAA'))).toBeNull());
it('should work with pattern string containing both boundary symbols', () =>
expect(Validators.pattern('^[aA]*$')(new FormControl('aaAA'))).toBeNull());
it('should work with pattern string containing only start boundary symbols', () =>
expect(Validators.pattern('^[aA]*')(new FormControl('aaAA'))).toBeNull());
it('should work with pattern string containing only end boundary symbols', () =>
expect(Validators.pattern('[aA]*$')(new FormControl('aaAA'))).toBeNull());
it('should work with pattern string not containing any boundary symbols', () =>
expect(Validators.pattern('[aA]*')(new FormControl('aaAA'))).toBeNull());
});
describe('compose', () => {
it('should return null when given null', () => {
expect(Validators.compose(null!)).toBe(null);
});
it('should collect errors from all the validators', () => {
const c = Validators.compose([validator('a', true), validator('b', true)])!;
expect(c(new FormControl(''))).toEqual({'a': true, 'b': true});
});
it('should run validators left to right', () => {
const c = Validators.compose([validator('a', 1), validator('a', 2)])!;
expect(c(new FormControl(''))).toEqual({'a': 2});
});
it('should return null when no errors', () => {
const c = Validators.compose([Validators.nullValidator, Validators.nullValidator])!;
expect(c(new FormControl(''))).toBeNull();
});
it('should ignore nulls', () => {
const c = Validators.compose([null!, Validators.required])!;
expect(c(new FormControl(''))).toEqual({'required': true});
});
}); | {
"end_byte": 16077,
"start_byte": 8020,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/validators_spec.ts"
} |
angular/packages/forms/test/validators_spec.ts_16083_22439 | describe('composeAsync', () => {
describe('promises', () => {
function promiseValidator(response: {[key: string]: any}): AsyncValidatorFn {
return (c: AbstractControl) => {
const res = c.value != 'expected' ? response : null;
return Promise.resolve(res);
};
}
it('should return null when given null', () => {
expect(Validators.composeAsync(null!)).toBeNull();
});
it('should collect errors from all the validators', fakeAsync(() => {
const v = Validators.composeAsync([
promiseValidator({'one': true}),
promiseValidator({'two': true}),
])!;
let errorMap: {[key: string]: any} | null = null;
(v(new FormControl('invalid')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors));
tick();
expect(errorMap!).toEqual({'one': true, 'two': true});
}));
it('should normalize and evaluate async validator-directives correctly', fakeAsync(() => {
const normalizedValidators = normalizeValidators<AsyncValidatorFn>([
new AsyncValidatorDirective('expected', {'one': true}),
]);
const validatorFn = Validators.composeAsync(normalizedValidators)!;
let errorMap: {[key: string]: any} | null = null;
(validatorFn(new FormControl('invalid')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors));
tick();
expect(errorMap!).toEqual({'one': true});
}));
it('should return null when no errors', fakeAsync(() => {
const v = Validators.composeAsync([promiseValidator({'one': true})])!;
let errorMap: {[key: string]: any} | null = undefined!;
(v(new FormControl('expected')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors));
tick();
expect(errorMap).toBeNull();
}));
it('should ignore nulls', fakeAsync(() => {
const v = Validators.composeAsync([promiseValidator({'one': true}), null!])!;
let errorMap: {[key: string]: any} | null = null;
(v(new FormControl('invalid')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors));
tick();
expect(errorMap!).toEqual({'one': true});
}));
});
describe('observables', () => {
function observableValidator(response: {[key: string]: any}): AsyncValidatorFn {
return (c: AbstractControl) => {
const res = c.value != 'expected' ? response : null;
return of(res);
};
}
it('should return null when given null', () => {
expect(Validators.composeAsync(null!)).toBeNull();
});
it('should collect errors from all the validators', () => {
const v = Validators.composeAsync([
observableValidator({'one': true}),
observableValidator({'two': true}),
])!;
let errorMap: {[key: string]: any} | null = null;
(v(new FormControl('invalid')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors));
expect(errorMap!).toEqual({'one': true, 'two': true});
});
it('should normalize and evaluate async validator-directives correctly', () => {
const normalizedValidators = normalizeValidators<AsyncValidatorFn>([
new AsyncValidatorDirective('expected', {'one': true}),
]);
const validatorFn = Validators.composeAsync(normalizedValidators)!;
let errorMap: {[key: string]: any} | null = null;
(validatorFn(new FormControl('invalid')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors))!;
expect(errorMap!).toEqual({'one': true});
});
it('should return null when no errors', () => {
const v = Validators.composeAsync([observableValidator({'one': true})])!;
let errorMap: {[key: string]: any} | null = undefined!;
(v(new FormControl('expected')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors));
expect(errorMap).toBeNull();
});
it('should ignore nulls', () => {
const v = Validators.composeAsync([observableValidator({'one': true}), null!])!;
let errorMap: {[key: string]: any} | null = null;
(v(new FormControl('invalid')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors));
expect(errorMap!).toEqual({'one': true});
});
it('should wait for all validators before setting errors', fakeAsync(() => {
function getTimerObs(time: number, errorMap: {[key: string]: any}): AsyncValidatorFn {
return (c: AbstractControl) => {
return timer(time).pipe(map(() => errorMap));
};
}
const v = Validators.composeAsync([
getTimerObs(100, {one: true}),
getTimerObs(200, {two: true}),
])!;
let errorMap: {[key: string]: any} | null | undefined = undefined;
(v(new FormControl('invalid')) as Observable<ValidationErrors | null>)
.pipe(first())
.subscribe((errors: {[key: string]: any} | null) => (errorMap = errors));
tick(100);
expect(errorMap).not.toBeDefined(
`Expected errors not to be set until all validators came back.`,
);
tick(100);
expect(errorMap!)
.withContext(`Expected errors to merge once all validators resolved.`)
.toEqual({one: true, two: true});
}));
});
});
});
})(); | {
"end_byte": 22439,
"start_byte": 16083,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/validators_spec.ts"
} |
angular/packages/forms/test/ng_control_status_spec.ts_0_1892 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {FormControl, FormsModule, ReactiveFormsModule, Validators} from '../public_api';
import {TestBed} from '@angular/core/testing';
import {provideExperimentalZonelessChangeDetection} from '@angular/core/src/change_detection/scheduling/zoneless_scheduling_impl';
describe('status host binding classes', () => {
beforeEach(() => {
TestBed.configureTestingModule({providers: [provideExperimentalZonelessChangeDetection()]});
});
it('work in OnPush components', async () => {
@Component({
selector: 'test-cmp',
template: `<input type="text" [formControl]="control">`,
standalone: true,
imports: [FormsModule, ReactiveFormsModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
class App {
control = new FormControl('old value', [Validators.required]);
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
expect(fixture.nativeElement.innerHTML).toContain('ng-valid');
expect(fixture.nativeElement.innerHTML).toContain('ng-untouched');
expect(fixture.nativeElement.innerHTML).toContain('ng-pristine');
fixture.componentInstance.control.setValue(null);
await fixture.whenStable();
expect(fixture.nativeElement.innerHTML).toContain('ng-invalid');
fixture.debugElement.query((x) => x.name === 'input').triggerEventHandler('blur');
await fixture.whenStable();
expect(fixture.nativeElement.innerHTML).toContain('ng-touched');
fixture.componentInstance.control.reset();
await fixture.whenStable();
expect(fixture.nativeElement.innerHTML).toContain('ng-untouched');
});
});
| {
"end_byte": 1892,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/ng_control_status_spec.ts"
} |
angular/packages/forms/test/util.ts_0_2871 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {EventEmitter} from '@angular/core';
import {AbstractControl, AsyncValidatorFn, ValidationErrors} from '@angular/forms';
import {of} from 'rxjs';
function createValidationPromise(
result: ValidationErrors | null,
timeout: number,
): Promise<ValidationErrors | null> {
return new Promise((resolve) => {
if (timeout == 0) {
resolve(result);
} else {
setTimeout(() => {
resolve(result);
}, timeout);
}
});
}
/**
* Returns a promise-based async validator that emits, after a delay, either:
* - an error `{async: true}` if the control value does not match the expected value
* - or null, otherwise
* The delay is either:
* - defined in `timeouts` parameter, as the association to the control value
* - or 0ms otherwise
*
* @param expected The expected control value
* @param timeouts A dictionary associating a control value to when the validation will trigger for
* that value
*/
export function asyncValidator(expected: string, timeouts = {}): AsyncValidatorFn {
return (control: AbstractControl) => {
const timeout = (timeouts as any)[control.value] ?? 0;
const result = control.value != expected ? {async: true} : null;
return createValidationPromise(result, timeout);
};
}
/**
* Returns an async validator that emits null or a custom error after a specified delay.
* If the delay is set to 0ms, the validator emits synchronously.
*
* @param timeout Indicates when the validator will emit
* @param shouldFail When true, a validation error is emitted, otherwise null is emitted
* @param customError When supplied, overrides the default error `{async: true}`
*/
export function simpleAsyncValidator({
timeout = 0,
shouldFail,
customError = {
async: true,
},
}: {
timeout?: number;
shouldFail: boolean;
customError?: any;
}): AsyncValidatorFn {
const result = shouldFail ? customError : null;
return (c: AbstractControl) =>
timeout === 0 ? of(result) : createValidationPromise(result, timeout);
}
/**
* Returns the asynchronous validation state of each provided control
* @param controls A collection of controls
*/
export function currentStateOf(
controls: AbstractControl[],
): {errors: any; pending: boolean; status: string}[] {
return controls.map((c) => ({errors: c.errors, pending: c.pending, status: c.status}));
}
/**
* Returns an `EventEmitter` emitting the default error `{'async': true}`
*
* @param c The control instance
*/
export function asyncValidatorReturningObservable(c: AbstractControl): EventEmitter<any> {
const e = new EventEmitter();
queueMicrotask(() => {
e.emit({'async': true});
});
return e;
}
| {
"end_byte": 2871,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/util.ts"
} |
angular/packages/forms/test/BUILD.bazel_0_1648 | load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library", "zone_compatible_jasmine_node_test")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/forms/index.mjs",
deps = ["//packages/forms"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
# Visible to //:saucelabs_unit_tests_poc target
visibility = ["//:__pkg__"],
deps = [
"//packages/common",
"//packages/core",
"//packages/core/testing",
"//packages/forms",
"//packages/platform-browser",
"//packages/platform-browser/testing",
"//packages/private/testing",
"@npm//rxjs",
],
)
# Tests rely on `async/await` for a `waitForAsync` test.
# This syntax needs to be downleveled until ZoneJS supports it.
zone_compatible_jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
tags = [
# disabled on 2020-04-14 due to failure on saucelabs monitor job
# https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645
# ```
# IE 11.0.0 (Windows 8.1.0.0) template-driven forms integration tests basic functionality should report properties which are written outside of template bindings FAILED
# InvalidStateError: InvalidStateError
# ```
"fixme-saucelabs",
],
deps = [
":test_lib",
],
)
| {
"end_byte": 1648,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/BUILD.bazel"
} |
angular/packages/forms/test/form_group_spec.ts_0_8266 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {
AbstractControl,
ControlEvent,
FormArray,
FormControl,
FormGroup,
ValidationErrors,
Validators,
ValueChangeEvent,
} from '@angular/forms';
import {of} from 'rxjs';
import {
asyncValidator,
asyncValidatorReturningObservable,
currentStateOf,
simpleAsyncValidator,
} from './util';
import {StatusChangeEvent} from '../src/model/abstract_model';
(function () {
function simpleValidator(c: AbstractControl): ValidationErrors | null {
return c.get('one')!.value === 'correct' ? null : {'broken': true};
}
function otherObservableValidator() {
return of({'other': true});
}
describe('FormGroup', () => {
describe('value', () => {
it('should be the reduced value of the child controls', () => {
const g = new FormGroup({'one': new FormControl('111'), 'two': new FormControl('222')});
expect(g.value).toEqual({'one': '111', 'two': '222'});
});
it('should be empty when there are no child controls', () => {
const g = new FormGroup({});
expect(g.value).toEqual({});
});
it('should support nested groups', () => {
const g = new FormGroup({
'one': new FormControl('111'),
'nested': new FormGroup({'two': new FormControl('222')}),
});
expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}});
(<FormControl>g.get('nested.two')).setValue('333');
expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}});
});
});
describe('getRawValue', () => {
let fg: FormGroup;
it('should work with nested form groups/arrays', () => {
fg = new FormGroup({
'c1': new FormControl('v1'),
'group': new FormGroup({'c2': new FormControl('v2'), 'c3': new FormControl('v3')}),
'array': new FormArray([new FormControl('v4'), new FormControl('v5')]),
});
fg.get('group')!.get('c3')!.disable();
(fg.get('array') as FormArray).at(1).disable();
expect(fg.getRawValue()).toEqual({
'c1': 'v1',
'group': {'c2': 'v2', 'c3': 'v3'},
'array': ['v4', 'v5'],
});
});
});
describe('markAllAsTouched', () => {
it('should mark all descendants as touched', () => {
const formGroup: FormGroup = new FormGroup({
'c1': new FormControl('v1'),
'group': new FormGroup({'c2': new FormControl('v2'), 'c3': new FormControl('v3')}),
'array': new FormArray([
new FormControl('v4') as any,
new FormControl('v5'),
new FormGroup({'c4': new FormControl('v4')}),
]),
});
expect(formGroup.touched).toBe(false);
const control1 = formGroup.get('c1') as FormControl;
expect(control1.touched).toBe(false);
const innerGroup = formGroup.get('group') as FormGroup;
expect(innerGroup.touched).toBe(false);
const innerGroupFirstChildCtrl = innerGroup.get('c2') as FormControl;
expect(innerGroupFirstChildCtrl.touched).toBe(false);
formGroup.markAllAsTouched();
expect(formGroup.touched).toBe(true);
expect(control1.touched).toBe(true);
expect(innerGroup.touched).toBe(true);
expect(innerGroupFirstChildCtrl.touched).toBe(true);
const innerGroupSecondChildCtrl = innerGroup.get('c3') as FormControl;
expect(innerGroupSecondChildCtrl.touched).toBe(true);
const array = formGroup.get('array') as FormArray;
expect(array.touched).toBe(true);
const arrayFirstChildCtrl = array.at(0) as FormControl;
expect(arrayFirstChildCtrl.touched).toBe(true);
const arraySecondChildCtrl = array.at(1) as FormControl;
expect(arraySecondChildCtrl.touched).toBe(true);
const arrayFirstChildGroup = array.at(2) as FormGroup;
expect(arrayFirstChildGroup.touched).toBe(true);
const arrayFirstChildGroupFirstChildCtrl = arrayFirstChildGroup.get('c4') as FormControl;
expect(arrayFirstChildGroupFirstChildCtrl.touched).toBe(true);
});
});
describe('adding and removing controls', () => {
let logger: any[];
beforeEach(() => {
logger = [];
});
it('should update value and validity when control is added', () => {
const g: FormGroup = new FormGroup({'one': new FormControl('1')});
expect(g.value).toEqual({'one': '1'});
expect(g.valid).toBe(true);
g.addControl('two', new FormControl('2', Validators.minLength(10)));
expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false);
});
it('should update value and validity when control is removed', () => {
const g: FormGroup = new FormGroup({
'one': new FormControl('1'),
'two': new FormControl('2', Validators.minLength(10)),
});
expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false);
g.removeControl('two');
expect(g.value).toEqual({'one': '1'});
expect(g.valid).toBe(true);
});
it('should not emit events when `FormGroup.addControl` is called with `emitEvent: false`', () => {
const g: FormGroup = new FormGroup({'one': new FormControl('1')});
expect(g.value).toEqual({'one': '1'});
g.valueChanges.subscribe(() => logger.push('value change'));
g.statusChanges.subscribe(() => logger.push('status change'));
g.addControl('two', new FormControl('2'), {emitEvent: false});
expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(logger).toEqual([]);
});
it('should not emit events when `FormGroup.removeControl` is called with `emitEvent: false`', () => {
const g: FormGroup = new FormGroup({
'one': new FormControl('1'),
'two': new FormControl('2', Validators.minLength(10)),
});
expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false);
g.valueChanges.subscribe(() => logger.push('value change'));
g.statusChanges.subscribe(() => logger.push('status change'));
g.removeControl('two', {emitEvent: false});
expect(g.value).toEqual({'one': '1'});
expect(g.valid).toBe(true);
expect(logger).toEqual([]);
});
it('should not emit status change events when `FormGroup.addControl` is called with `emitEvent: false`', () => {
const validatorFn = (value: any) =>
value.controls.invalidCtrl ? {invalidCtrl: true} : null;
const asyncValidatorFn = (value: any) => of(validatorFn(value));
const g: FormGroup = new FormGroup({}, validatorFn, asyncValidatorFn);
expect(g.valid).toBe(true);
g.statusChanges.subscribe(() => logger.push('status change'));
g.addControl('invalidCtrl', new FormControl(''), {emitEvent: false});
expect(g.value).toEqual({'invalidCtrl': ''});
expect(g.valid).toBe(false);
expect(logger).toEqual([]);
});
});
describe('dirty', () => {
let c: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('value');
g = new FormGroup({'one': c});
});
it('should be false after creating a control', () => {
expect(g.dirty).toEqual(false);
});
it('should be true after changing the value of the control', () => {
c.markAsDirty();
expect(g.dirty).toEqual(true);
});
});
describe('touched', () => {
let c: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('value');
g = new FormGroup({'one': c});
});
it('should be false after creating a control', () => {
expect(g.touched).toEqual(false);
});
it('should be true after control is marked as touched', () => {
c.markAsTouched();
expect(g.touched).toEqual(true);
});
}); | {
"end_byte": 8266,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_8272_13224 | describe('setValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value', () => {
g.setValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set child values', () => {
g.setValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should set child control values if disabled', () => {
c2.disable();
g.setValue({'one': 'one', 'two': 'two'});
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one'});
expect(g.getRawValue()).toEqual({'one': 'one', 'two': 'two'});
});
it('should set group value if group is disabled', () => {
g.disable();
g.setValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set parent values', () => {
const form = new FormGroup({'parent': g});
g.setValue({'one': 'one', 'two': 'two'});
expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'parent': g});
g.setValue({'one': 'one', 'two': 'two'}, {onlySelf: true});
expect(form.value).toEqual({parent: {'one': '', 'two': ''}});
});
it('should throw if fields are missing from supplied value (subset)', () => {
expect(() => g.setValue({'one': 'one'})).toThrowError(
new RegExp(`NG01002: Must supply a value for form control with name: 'two'`),
);
});
it('should throw if a value is provided for a missing control (superset)', () => {
expect(() => g.setValue({'one': 'one', 'two': 'two', 'three': 'three'})).toThrowError(
new RegExp(`NG01001: Cannot find form control with name: 'three'`),
);
});
it('should throw if a value is not provided for a disabled control', () => {
c2.disable();
expect(() => g.setValue({'one': 'one'})).toThrowError(
new RegExp(`NG01002: Must supply a value for form control with name: 'two'`),
);
});
it('should throw if no controls are set yet', () => {
const empty = new FormGroup({});
expect(() =>
empty.setValue({
'one': 'one',
}),
).toThrowError(new RegExp(`no form controls registered with this group`));
});
describe('setValue() events', () => {
let form: FormGroup;
let logger: any[];
beforeEach(() => {
form = new FormGroup({'parent': g});
logger = [];
});
it('should emit one valueChange event per control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.setValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not emit events when `FormGroup.setValue` is called with `emitEvent: false`', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control'));
g.setValue({'one': 'one', 'two': 'two'}, {emitEvent: false});
expect(logger).toEqual([]);
});
it('should emit one statusChange event per control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
g.setValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not emit events on the parent when called with `emitEvent: false`', () => {
form.valueChanges.subscribe(() => logger.push('form value change'));
g.valueChanges.subscribe(() => logger.push('group value change'));
form.statusChanges.subscribe(() => logger.push('form status change'));
g.statusChanges.subscribe(() => logger.push('group status change'));
g.addControl('three', new FormControl(5), {emitEvent: false});
expect(logger).toEqual([]);
});
});
}); | {
"end_byte": 13224,
"start_byte": 8272,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_13230_19230 | describe('patchValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup, g2: FormGroup;
beforeEach(() => {
c = new FormControl('');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
g2 = new FormGroup({
'array': new FormArray([new FormControl(1), new FormControl(2)]),
'group': new FormGroup({'one': new FormControl(3)}),
});
});
it('should set its own value', () => {
g.patchValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set child values', () => {
g.patchValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should patch disabled control values', () => {
c2.disable();
g.patchValue({'one': 'one', 'two': 'two'});
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one'});
expect(g.getRawValue()).toEqual({'one': 'one', 'two': 'two'});
});
it('should patch disabled control groups', () => {
g.disable();
g.patchValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set parent values', () => {
const form = new FormGroup({'parent': g});
g.patchValue({'one': 'one', 'two': 'two'});
expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'parent': g});
g.patchValue({'one': 'one', 'two': 'two'}, {onlySelf: true});
expect(form.value).toEqual({parent: {'one': '', 'two': ''}});
});
it('should ignore fields that are missing from supplied value (subset)', () => {
g.patchValue({'one': 'one'});
expect(g.value).toEqual({'one': 'one', 'two': ''});
});
it('should not ignore fields that are null', () => {
g.patchValue({'one': null});
expect(g.value).toEqual({'one': null, 'two': ''});
});
it('should ignore any value provided for a missing control (superset)', () => {
g.patchValue({'three': 'three'});
expect(g.value).toEqual({'one': '', 'two': ''});
});
it('should ignore a control if `null` or `undefined` are used as values', () => {
const INITIAL_STATE = {'array': [1, 2], 'group': {'one': 3}};
g2.patchValue({'array': null});
expect(g2.value).toEqual(INITIAL_STATE);
g2.patchValue({'array': undefined});
expect(g2.value).toEqual(INITIAL_STATE);
g2.patchValue({'group': null});
expect(g2.value).toEqual(INITIAL_STATE);
g2.patchValue({'group': undefined});
expect(g2.value).toEqual(INITIAL_STATE);
});
describe('patchValue() events', () => {
let form: FormGroup;
let logger: any[];
beforeEach(() => {
form = new FormGroup({'parent': g});
logger = [];
});
it('should emit one valueChange event per control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not emit valueChange events for skipped controls', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one'});
expect(logger).toEqual(['control1', 'group', 'form']);
});
it('should not emit valueChange events for skipped controls (represented as `null` or `undefined`)', () => {
const logEvent = () => logger.push('valueChanges event');
const [formArrayControl1, formArrayControl2] = (g2.controls['array'] as FormArray)
.controls;
const formGroupControl = (g2.controls['group'] as FormGroup).controls['one'];
formArrayControl1.valueChanges.subscribe(logEvent);
formArrayControl2.valueChanges.subscribe(logEvent);
formGroupControl.valueChanges.subscribe(logEvent);
g2.patchValue({'array': null});
g2.patchValue({'array': undefined});
g2.patchValue({'group': null});
g2.patchValue({'group': undefined});
// No events are expected in `valueChanges` since
// all controls were skipped in `patchValue`.
expect(logger).toEqual([]);
});
it('should not emit events when `FormGroup.patchValue` is called with `emitEvent: false`', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control'));
g.patchValue({'one': 'one', 'two': 'two'}, {emitEvent: false});
expect(logger).toEqual([]);
});
it('should emit one statusChange event per control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
});
}); | {
"end_byte": 19230,
"start_byte": 13230,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_19236_27670 | describe('reset()', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('initial value');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value if value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(g.value).toEqual({'one': 'initial value', 'two': ''});
});
it('should set its own value if boxed value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': {value: 'initial value', disabled: false}, 'two': ''});
expect(g.value).toEqual({'one': 'initial value', 'two': ''});
});
it('should clear its own value if no value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(g.value).toEqual({'one': null, 'two': null});
});
it('should set the value of each of its child controls if value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(c.value).toBe('initial value');
expect(c2.value).toBe('');
});
it('should clear the value of each of its child controls if no value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(c.value).toBe(null);
expect(c2.value).toBe(null);
});
it('should set the value of its parent if value passed', () => {
const form = new FormGroup({'g': g});
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(form.value).toEqual({'g': {'one': 'initial value', 'two': ''}});
});
it('should clear the value of its parent if no value passed', () => {
const form = new FormGroup({'g': g});
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(form.value).toEqual({'g': {'one': null, 'two': null}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'g': g});
g.reset({'one': 'new value', 'two': 'new value'}, {onlySelf: true});
expect(form.value).toEqual({g: {'one': 'initial value', 'two': ''}});
});
it('should mark itself as pristine', () => {
g.markAsDirty();
expect(g.pristine).toBe(false);
g.reset();
expect(g.pristine).toBe(true);
});
it('should mark all child controls as pristine', () => {
c.markAsDirty();
c2.markAsDirty();
expect(c.pristine).toBe(false);
expect(c2.pristine).toBe(false);
g.reset();
expect(c.pristine).toBe(true);
expect(c2.pristine).toBe(true);
});
it('should mark the parent as pristine if all siblings pristine', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsDirty();
expect(form.pristine).toBe(false);
g.reset();
expect(form.pristine).toBe(true);
});
it('should not mark the parent pristine if any dirty siblings', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsDirty();
c3.markAsDirty();
expect(form.pristine).toBe(false);
g.reset();
expect(form.pristine).toBe(false);
});
it('should mark itself as untouched', () => {
g.markAsTouched();
expect(g.untouched).toBe(false);
g.reset();
expect(g.untouched).toBe(true);
});
it('should mark all child controls as untouched', () => {
c.markAsTouched();
c2.markAsTouched();
expect(c.untouched).toBe(false);
expect(c2.untouched).toBe(false);
g.reset();
expect(c.untouched).toBe(true);
expect(c2.untouched).toBe(true);
});
it('should mark the parent untouched if all siblings untouched', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsTouched();
expect(form.untouched).toBe(false);
g.reset();
expect(form.untouched).toBe(true);
});
it('should not mark the parent untouched if any touched siblings', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsTouched();
c3.markAsTouched();
expect(form.untouched).toBe(false);
g.reset();
expect(form.untouched).toBe(false);
});
it('should retain previous disabled state', () => {
g.disable();
g.reset();
expect(g.disabled).toBe(true);
});
it('should set child disabled state if boxed value passed', () => {
g.disable();
g.reset({'one': {value: '', disabled: false}, 'two': ''});
expect(c.disabled).toBe(false);
expect(g.disabled).toBe(false);
});
it('should be able to reset a nested control with null', () => {
const g = new FormGroup({
id: new FormControl(2),
nested: new FormGroup<any>({
id: new FormControl(3),
}),
});
g.reset({id: 1, nested: null});
expect(g.get('nested')?.value).toEqual({id: null});
expect(g.get('nested.id')?.value).toBe(null);
});
describe('reset() events', () => {
let form: FormGroup, c3: FormControl, logger: any[];
beforeEach(() => {
c3 = new FormControl('');
form = new FormGroup({'g': g, 'c3': c3});
logger = [];
});
it('should emit one valueChange event per reset control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
c3.valueChanges.subscribe(() => logger.push('control3'));
g.reset();
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not emit events when `FormGroup.reset` is called with `emitEvent: false`', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control'));
g.reset({}, {emitEvent: false});
expect(logger).toEqual([]);
});
it('should emit one statusChange event per reset control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
c3.statusChanges.subscribe(() => logger.push('control3'));
g.reset();
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should emit one statusChange event per reset control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
c3.statusChanges.subscribe(() => logger.push('control3'));
g.reset({'one': {value: '', disabled: true}});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should mark as pristine and not dirty before emitting valueChange and statusChange events when resetting', () => {
const pristineAndNotDirty = () => {
expect(form.pristine).toBe(true);
expect(form.dirty).toBe(false);
};
c3.markAsDirty();
expect(form.pristine).toBe(false);
expect(form.dirty).toBe(true);
form.valueChanges.subscribe(pristineAndNotDirty);
form.statusChanges.subscribe(pristineAndNotDirty);
form.reset();
});
});
}); | {
"end_byte": 27670,
"start_byte": 19236,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_27676_35934 | describe('contains', () => {
let group: FormGroup;
beforeEach(() => {
group = new FormGroup({
'required': new FormControl('requiredValue'),
'optional': new FormControl({value: 'disabled value', disabled: true}),
});
});
it('should return false when the component is disabled', () => {
expect(group.contains('optional')).toEqual(false);
});
it('should return false when there is no component with the given name', () => {
expect(group.contains('something else')).toEqual(false);
});
it('should return true when the component is enabled', () => {
expect(group.contains('required')).toEqual(true);
group.enable();
expect(group.contains('optional')).toEqual(true);
});
it('should support controls with dots in their name', () => {
expect(group.contains('some.name')).toBe(false);
group.addControl('some.name', new FormControl());
expect(group.contains('some.name')).toBe(true);
});
});
describe('retrieve', () => {
let group: FormGroup;
beforeEach(() => {
group = new FormGroup({
'required': new FormControl('requiredValue'),
});
});
it('should not get inherited properties', () => {
expect(group.get('constructor')).toBe(null);
});
});
describe('statusChanges', () => {
let control: FormControl;
let group: FormGroup;
beforeEach(waitForAsync(() => {
control = new FormControl('', null, asyncValidatorReturningObservable);
group = new FormGroup({'one': control});
}));
it('should fire statusChanges events for async validators added via options object', fakeAsync(() => {
// The behavior can be tested for each of the model types.
let statuses: string[] = [];
// Create a form control with an async validator added via options object.
const asc = new FormGroup({}, {asyncValidators: [() => Promise.resolve(null)]});
// Subscribe to status changes.
asc.statusChanges.subscribe((status: any) => statuses.push(status));
// After a tick, the async validator should change status PENDING -> VALID.
tick();
expect(statuses).toEqual(['VALID']);
}));
it('should fire a statusChange if child has async validation change', fakeAsync(() => {
const loggedValues: string[] = [];
group.statusChanges.subscribe((status) => loggedValues.push(status));
control.setValue('');
tick();
expect(loggedValues).toEqual(['PENDING', 'INVALID']);
}));
});
describe('getError', () => {
it('should return the error when it is present', () => {
const c = new FormControl('', Validators.required);
const g = new FormGroup({'one': c});
expect(c.getError('required')).toEqual(true);
expect(g.getError('required', ['one'])).toEqual(true);
});
it('should return null otherwise', () => {
const c = new FormControl('not empty', Validators.required);
const g = new FormGroup({'one': c});
expect(c.getError('invalid')).toEqual(null);
expect(g.getError('required', ['one'])).toEqual(null);
expect(g.getError('required', ['invalid'])).toEqual(null);
});
it('should be able to traverse group with single string', () => {
const c = new FormControl('', Validators.required);
const g = new FormGroup({'one': c});
expect(c.getError('required')).toEqual(true);
expect(g.getError('required', 'one')).toEqual(true);
});
it('should be able to traverse group with string delimited by dots', () => {
const c = new FormControl('', Validators.required);
const g2 = new FormGroup({'two': c});
const g1 = new FormGroup({'one': g2});
expect(c.getError('required')).toEqual(true);
expect(g1.getError('required', 'one.two')).toEqual(true);
});
it('should traverse group with form array using string and numbers', () => {
const c = new FormControl('', Validators.required);
const g2 = new FormGroup({'two': c});
const a = new FormArray([g2]);
const g1 = new FormGroup({'one': a});
expect(c.getError('required')).toEqual(true);
expect(g1.getError('required', ['one', 0, 'two'])).toEqual(true);
});
});
describe('hasError', () => {
it('should return true when it is present', () => {
const c = new FormControl('', Validators.required);
const g = new FormGroup({'one': c});
expect(c.hasError('required')).toEqual(true);
expect(g.hasError('required', ['one'])).toEqual(true);
});
it('should return false otherwise', () => {
const c = new FormControl('not empty', Validators.required);
const g = new FormGroup({'one': c});
expect(c.hasError('invalid')).toEqual(false);
expect(g.hasError('required', ['one'])).toEqual(false);
expect(g.hasError('required', ['invalid'])).toEqual(false);
});
it('should be able to traverse group with single string', () => {
const c = new FormControl('', Validators.required);
const g = new FormGroup({'one': c});
expect(c.hasError('required')).toEqual(true);
expect(g.hasError('required', 'one')).toEqual(true);
});
it('should be able to traverse group with string delimited by dots', () => {
const c = new FormControl('', Validators.required);
const g2 = new FormGroup({'two': c});
const g1 = new FormGroup({'one': g2});
expect(c.hasError('required')).toEqual(true);
expect(g1.hasError('required', 'one.two')).toEqual(true);
});
it('should traverse group with form array using string and numbers', () => {
const c = new FormControl('', Validators.required);
const g2 = new FormGroup({'two': c});
const a = new FormArray([g2]);
const g1 = new FormGroup({'one': a});
expect(c.getError('required')).toEqual(true);
expect(g1.getError('required', ['one', 0, 'two'])).toEqual(true);
});
});
describe('validator', () => {
function containsValidator(c: AbstractControl): ValidationErrors | null {
return c.get('one')!.value && c.get('one')!.value.indexOf('c') !== -1
? null
: {'missing': true};
}
it('should run a single validator when the value changes', () => {
const c: FormControl = new FormControl(null);
const g = new FormGroup({'one': c}, simpleValidator);
c.setValue('correct');
expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null);
c.setValue('incorrect');
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({'broken': true});
});
it('should support multiple validators from array', () => {
const g = new FormGroup({one: new FormControl()}, [simpleValidator, containsValidator]);
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({missing: true, broken: true});
g.setValue({one: 'c'});
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({broken: true});
g.setValue({one: 'correct'});
expect(g.valid).toEqual(true);
});
it('should set single validator from options obj', () => {
const g = new FormGroup({one: new FormControl()}, {validators: simpleValidator});
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({broken: true});
g.setValue({one: 'correct'});
expect(g.valid).toEqual(true);
});
it('should set multiple validators from options obj', () => {
const g = new FormGroup(
{one: new FormControl()},
{validators: [simpleValidator, containsValidator]},
);
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({missing: true, broken: true});
g.setValue({one: 'c'});
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({broken: true});
g.setValue({one: 'correct'});
expect(g.valid).toEqual(true);
});
}); | {
"end_byte": 35934,
"start_byte": 27676,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_35940_44145 | describe('asyncValidator', () => {
it('should run the async validator', fakeAsync(() => {
const c = new FormControl('value');
const g = new FormGroup({'one': c}, null!, asyncValidator('expected'));
expect(g.pending).toEqual(true);
tick(1);
expect(g.errors).toEqual({'async': true});
expect(g.pending).toEqual(false);
}));
it('should set multiple async validators from array', fakeAsync(() => {
const g = new FormGroup({'one': new FormControl('value')}, null!, [
asyncValidator('expected'),
otherObservableValidator,
]);
expect(g.pending).toEqual(true);
tick();
expect(g.errors).toEqual({'async': true, 'other': true});
expect(g.pending).toEqual(false);
}));
it('should set single async validator from options obj', fakeAsync(() => {
const g = new FormGroup(
{'one': new FormControl('value')},
{asyncValidators: asyncValidator('expected')},
);
expect(g.pending).toEqual(true);
tick();
expect(g.errors).toEqual({'async': true});
expect(g.pending).toEqual(false);
}));
it('should set multiple async validators from options obj', fakeAsync(() => {
const g = new FormGroup(
{'one': new FormControl('value')},
{asyncValidators: [asyncValidator('expected'), otherObservableValidator]},
);
expect(g.pending).toEqual(true);
tick();
expect(g.errors).toEqual({'async': true, 'other': true});
expect(g.pending).toEqual(false);
}));
it("should set the parent group's status to pending", fakeAsync(() => {
const c = new FormControl('value', null!, asyncValidator('expected'));
const g = new FormGroup({'one': c});
expect(g.pending).toEqual(true);
tick(1);
expect(g.pending).toEqual(false);
}));
it("should run the parent group's async validator when children are pending", fakeAsync(() => {
const c = new FormControl('value', null!, asyncValidator('expected'));
const g = new FormGroup({'one': c}, null!, asyncValidator('expected'));
tick(1);
expect(g.errors).toEqual({'async': true});
expect(g.get('one')!.errors).toEqual({'async': true});
}));
it('should handle successful async FormGroup resolving synchronously before a successful async child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 0, shouldFail: false}),
);
// Initially, the form control validation is pending, and the form group own validation has
// synchronously resolved. Still, the form is in pending state due to its child
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, the form control validation has resolved
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle successful async FormGroup resolving after a synchronously and successfully resolving child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 0, shouldFail: false}),
);
const g = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
// Initially, form control validator has synchronously resolved. However, g has its own
// pending validation
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, the form group validation has resolved
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle successful async FormGroup and child control validators resolving synchronously', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 0, shouldFail: false}),
);
const g = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 0, shouldFail: false}),
);
// Both form control and form group successful async validators have resolved synchronously
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle failing async FormGroup and failing child control validators resolving synchronously', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 0, shouldFail: true}),
);
const g = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 0, shouldFail: true}),
);
// FormControl async validator has executed and failed synchronously with the default error
// `{async: true}`. Next, the form group status is calculated. Since one of its children is
// failing, the form group itself is marked `INVALID`. And its asynchronous validation is
// not even triggered. Therefore, we end up with form group that is `INVALID` but whose
// errors are null (child errors do not propagate and own async validation not event
// triggered).
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: false, status: 'INVALID'}, // Group
{errors: {async: true}, pending: false, status: 'INVALID'}, // Control
]);
}));
it('should handle failing async FormGroup and successful child control validators resolving synchronously', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 0, shouldFail: false}),
);
const g = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 0, shouldFail: true}),
);
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle failing async FormArray and successful children validators resolving synchronously', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 0, shouldFail: false}),
);
const g: FormGroup = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 0, shouldFail: false}),
);
const c2 = new FormControl(
'fcVal',
null!,
simpleAsyncValidator({timeout: 0, shouldFail: false}),
);
const a = new FormArray(
[g as any, c2],
null!,
simpleAsyncValidator({timeout: 0, shouldFail: true}),
);
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Array
{errors: null, pending: false, status: 'VALID'}, // Group p
{errors: null, pending: false, status: 'VALID'}, // Control c2
]);
})); | {
"end_byte": 44145,
"start_byte": 35940,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_44153_50185 | it('should handle failing FormGroup validator resolving after successful child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 2, shouldFail: true}),
);
// Initially, the form group and nested control are in pending state
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, only form control validation has resolved
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, the form group validation fails
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle failing FormArray validator resolving after successful child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const a = new FormArray([c], null!, simpleAsyncValidator({timeout: 2, shouldFail: true}));
// Initially, the form array and nested control are in pending state
expect(currentStateOf([a, a.at(0)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, only form control validation has resolved
expect(currentStateOf([a, a.at(0)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, the form array validation fails
expect(currentStateOf([a, a.at(0)!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle successful FormGroup validator resolving after successful child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 2, shouldFail: false}),
);
// Initially, the form group and nested control are in pending state
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, only form control validation has resolved
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, the form group validation resolves
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle successful FormArray validator resolving after successful child validators', fakeAsync(() => {
const c1 = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g = new FormGroup(
{'one': c1},
null!,
simpleAsyncValidator({timeout: 2, shouldFail: false}),
);
const c2 = new FormControl(
'fcVal',
null!,
simpleAsyncValidator({timeout: 3, shouldFail: false}),
);
const a = new FormArray(
[g as any, c2],
null!,
simpleAsyncValidator({timeout: 4, shouldFail: false}),
);
// Initially, the form array and the tested form group and form control c2 are in pending
// state
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: true, status: 'PENDING'}, // g
{errors: null, pending: true, status: 'PENDING'}, // c2
]);
tick(2);
// After 2ms, g validation has resolved
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // g
{errors: null, pending: true, status: 'PENDING'}, // c2
]);
tick(1);
// After 1ms, c2 validation has resolved
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // g
{errors: null, pending: false, status: 'VALID'}, // c2
]);
tick(1);
// After 1ms, FormArray own validation has resolved
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // g
{errors: null, pending: false, status: 'VALID'}, // c2
]);
})); | {
"end_byte": 50185,
"start_byte": 44153,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_50193_57480 | it('should handle failing FormArray validator resolving after successful child validators', fakeAsync(() => {
const c1 = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g = new FormGroup(
{'one': c1},
null!,
simpleAsyncValidator({timeout: 2, shouldFail: false}),
);
const c2 = new FormControl(
'fcVal',
null!,
simpleAsyncValidator({timeout: 3, shouldFail: false}),
);
const a = new FormArray(
[g as any, c2],
null!,
simpleAsyncValidator({timeout: 4, shouldFail: true}),
);
// Initially, the form array and the tested form group and form control c2 are in pending
// state
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: true, status: 'PENDING'}, // g
{errors: null, pending: true, status: 'PENDING'}, // c2
]);
tick(2);
// After 2ms, g validation has resolved
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // g
{errors: null, pending: true, status: 'PENDING'}, // c2
]);
tick(1);
// After 1ms, c2 validation has resolved
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // g
{errors: null, pending: false, status: 'VALID'}, // c2
]);
tick(1);
// After 1ms, FormArray own validation has failed
expect(currentStateOf([a, a.at(0)!, a.at(1)!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // g
{errors: null, pending: false, status: 'VALID'}, // c2
]);
}));
it('should handle multiple successful FormGroup validators resolving after successful child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g = new FormGroup({'one': c}, null!, [
simpleAsyncValidator({timeout: 2, shouldFail: false}),
simpleAsyncValidator({timeout: 3, shouldFail: false}),
]);
// Initially, the form group and nested control are in pending state
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, only form control validation has resolved
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, one form async validator has resolved but not the second
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, the form group validation resolves
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle multiple FormGroup validators (success then failure) resolving after successful child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g = new FormGroup({'one': c}, null!, [
simpleAsyncValidator({timeout: 2, shouldFail: false}),
simpleAsyncValidator({timeout: 3, shouldFail: true}),
]);
// Initially, the form group and nested control are in pending state
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, only form control validation has resolved
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, one form async validator has resolved but not the second
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, the form group validation fails
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle multiple FormGroup validators (failure then success) resolving after successful child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g = new FormGroup({'one': c}, null!, [
simpleAsyncValidator({timeout: 2, shouldFail: true}),
simpleAsyncValidator({timeout: 3, shouldFail: false}),
]);
// Initially, the form group and nested control are in pending state
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, only form control validation has resolved
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// All async validators are composed into one function. So, after 2ms, the FormGroup g is
// still in pending state without errors
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
tick(1);
// After 1ms, the form group validation fails
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
})); | {
"end_byte": 57480,
"start_byte": 50193,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_57488_62483 | it('should handle async validators in nested form groups / arrays', fakeAsync(() => {
const c1 = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 1, shouldFail: false}),
);
const g1 = new FormGroup(
{'one': c1},
null!,
simpleAsyncValidator({timeout: 2, shouldFail: true}),
);
const c2 = new FormControl(
'fcVal',
null!,
simpleAsyncValidator({timeout: 3, shouldFail: false}),
);
const g2 = new FormArray(
[c2],
null!,
simpleAsyncValidator({timeout: 4, shouldFail: false}),
);
const g = new FormGroup(
{'g1': g1, 'g2': g2},
null!,
simpleAsyncValidator({timeout: 5, shouldFail: false}),
);
// Initially, the form group and nested control are in pending state
expect(currentStateOf([g, g.get('g1')!, g.get('g2')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group g
{errors: null, pending: true, status: 'PENDING'}, // Group g1
{errors: null, pending: true, status: 'PENDING'}, // Group g2
]);
tick(2);
// After 2ms, g1 validation fails
expect(currentStateOf([g, g.get('g1')!, g.get('g2')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group g
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group g1
{errors: null, pending: true, status: 'PENDING'}, // Group g2
]);
tick(2);
// After 2ms, g2 validation resolves
expect(currentStateOf([g, g.get('g1')!, g.get('g2')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group g
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group g1
{errors: null, pending: false, status: 'VALID'}, // Group g2
]);
tick(1);
// After 1ms, g validation fails because g1 is invalid, but since errors do not cascade, so
// we still have null errors for g
expect(currentStateOf([g, g.get('g1')!, g.get('g2')!])).toEqual([
{errors: null, pending: false, status: 'INVALID'}, // Group g
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group g1
{errors: null, pending: false, status: 'VALID'}, // Group g2
]);
}));
it('should handle failing FormGroup validator resolving before successful child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 2, shouldFail: false}),
);
const g = new FormGroup(
{'one': c},
null!,
simpleAsyncValidator({timeout: 1, shouldFail: true}),
);
// Initially, the form group and nested control are in pending state
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, form group validation fails
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, child validation resolves
expect(currentStateOf([g, g.get('one')!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
it('should handle failing FormArray validator resolving before successful child validator', fakeAsync(() => {
const c = new FormControl(
'fcValue',
null!,
simpleAsyncValidator({timeout: 2, shouldFail: false}),
);
const a = new FormArray([c], null!, simpleAsyncValidator({timeout: 1, shouldFail: true}));
// Initially, the form array and nested control are in pending state
expect(currentStateOf([a, a.at(0)!])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // FormArray
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, form array validation fails
expect(currentStateOf([a, a.at(0)!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // FormArray
{errors: null, pending: true, status: 'PENDING'}, // Control
]);
tick(1);
// After 1ms, child validation resolves
expect(currentStateOf([a, a.at(0)!])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // FormArray
{errors: null, pending: false, status: 'VALID'}, // Control
]);
}));
}); | {
"end_byte": 62483,
"start_byte": 57488,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_62489_71867 | describe('disable() & enable()', () => {
it('should mark the group as disabled', () => {
const g = new FormGroup({'one': new FormControl(null)});
expect(g.disabled).toBe(false);
expect(g.valid).toBe(true);
g.disable();
expect(g.disabled).toBe(true);
expect(g.valid).toBe(false);
g.enable();
expect(g.disabled).toBe(false);
expect(g.valid).toBe(true);
});
it('should set the group status as disabled', () => {
const g = new FormGroup({'one': new FormControl(null)});
expect(g.status).toEqual('VALID');
g.disable();
expect(g.status).toEqual('DISABLED');
g.enable();
expect(g.status).toBe('VALID');
});
it('should mark children of the group as disabled', () => {
const c1 = new FormControl(null);
const c2 = new FormControl(null);
const g = new FormGroup({'one': c1, 'two': c2});
expect(c1.disabled).toBe(false);
expect(c2.disabled).toBe(false);
g.disable();
expect(c1.disabled).toBe(true);
expect(c2.disabled).toBe(true);
g.enable();
expect(c1.disabled).toBe(false);
expect(c2.disabled).toBe(false);
});
it('should ignore disabled controls in validation', () => {
const g = new FormGroup({
nested: new FormGroup({one: new FormControl(null, Validators.required)}),
two: new FormControl('two'),
});
expect(g.valid).toBe(false);
g.get('nested')!.disable();
expect(g.valid).toBe(true);
g.get('nested')!.enable();
expect(g.valid).toBe(false);
});
it('should ignore disabled controls when serializing value', () => {
const g = new FormGroup({
nested: new FormGroup({one: new FormControl('one')}),
two: new FormControl('two'),
});
expect(g.value).toEqual({'nested': {'one': 'one'}, 'two': 'two'});
g.get('nested')!.disable();
expect(g.value).toEqual({'two': 'two'});
g.get('nested')!.enable();
expect(g.value).toEqual({'nested': {'one': 'one'}, 'two': 'two'});
});
it('should update its value when disabled with disabled children', () => {
const g = new FormGroup({
nested: new FormGroup({one: new FormControl('one'), two: new FormControl('two')}),
});
g.get('nested.two')!.disable();
expect(g.value).toEqual({nested: {one: 'one'}});
g.get('nested')!.disable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
g.get('nested')!.enable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
});
it('should update its value when enabled with disabled children', () => {
const g = new FormGroup({
nested: new FormGroup({one: new FormControl('one'), two: new FormControl('two')}),
});
g.get('nested.two')!.disable();
expect(g.value).toEqual({nested: {one: 'one'}});
g.get('nested')!.enable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
});
it('should ignore disabled controls when determining dirtiness', () => {
const g = new FormGroup({
nested: new FormGroup({one: new FormControl('one')}),
two: new FormControl('two'),
});
g.get('nested.one')!.markAsDirty();
expect(g.dirty).toBe(true);
g.get('nested')!.disable();
expect(g.get('nested')!.dirty).toBe(true);
expect(g.dirty).toEqual(false);
g.get('nested')!.enable();
expect(g.dirty).toEqual(true);
});
it('should ignore disabled controls when determining touched state', () => {
const g = new FormGroup({
nested: new FormGroup({one: new FormControl('one')}),
two: new FormControl('two'),
});
g.get('nested.one')!.markAsTouched();
expect(g.touched).toBe(true);
g.get('nested')!.disable();
expect(g.get('nested')!.touched).toBe(true);
expect(g.touched).toEqual(false);
g.get('nested')!.enable();
expect(g.touched).toEqual(true);
});
it('should keep empty, disabled groups disabled when updating validity', () => {
const group: FormGroup = new FormGroup({});
expect(group.status).toEqual('VALID');
group.disable();
expect(group.status).toEqual('DISABLED');
group.updateValueAndValidity();
expect(group.status).toEqual('DISABLED');
group.addControl('one', new FormControl({value: '', disabled: true}));
expect(group.status).toEqual('DISABLED');
group.addControl('two', new FormControl());
expect(group.status).toEqual('VALID');
});
it('should re-enable empty, disabled groups', () => {
const group = new FormGroup({});
group.disable();
expect(group.status).toEqual('DISABLED');
group.enable();
expect(group.status).toEqual('VALID');
});
it('should not run validators on disabled controls', () => {
const validator = jasmine.createSpy('validator');
const g = new FormGroup({'one': new FormControl()}, validator);
expect(validator.calls.count()).toEqual(1);
g.disable();
expect(validator.calls.count()).toEqual(1);
g.setValue({one: 'value'});
expect(validator.calls.count()).toEqual(1);
g.enable();
expect(validator.calls.count()).toEqual(2);
});
describe('disabled errors', () => {
it('should clear out group errors when disabled', () => {
const g = new FormGroup({'one': new FormControl()}, () => ({'expected': true}));
expect(g.errors).toEqual({'expected': true});
g.disable();
expect(g.errors).toEqual(null);
g.enable();
expect(g.errors).toEqual({'expected': true});
});
it('should re-populate group errors when enabled from a child', () => {
const g: FormGroup = new FormGroup({'one': new FormControl()}, () => ({
'expected': true,
}));
g.disable();
expect(g.errors).toEqual(null);
g.addControl('two', new FormControl());
expect(g.errors).toEqual({'expected': true});
});
it('should clear out async group errors when disabled', fakeAsync(() => {
const g = new FormGroup({'one': new FormControl()}, null!, asyncValidator('expected'));
tick();
expect(g.errors).toEqual({'async': true});
g.disable();
expect(g.errors).toEqual(null);
g.enable();
tick();
expect(g.errors).toEqual({'async': true});
}));
it('should re-populate async group errors when enabled from a child', fakeAsync(() => {
const g: FormGroup = new FormGroup(
{'one': new FormControl()},
null!,
asyncValidator('expected'),
);
tick();
expect(g.errors).toEqual({'async': true});
g.disable();
expect(g.errors).toEqual(null);
g.addControl('two', new FormControl());
tick();
expect(g.errors).toEqual({'async': true});
}));
});
describe('disabled events', () => {
let logger: string[];
let c: FormControl;
let g: FormGroup;
let form: FormGroup;
beforeEach(() => {
logger = [];
c = new FormControl('', Validators.required);
g = new FormGroup({one: c});
form = new FormGroup({g: g});
});
it('should emit value change events in the right order', () => {
c.valueChanges.subscribe(() => logger.push('control'));
g.valueChanges.subscribe(() => logger.push('group'));
form.valueChanges.subscribe(() => logger.push('form'));
g.disable();
expect(logger).toEqual(['control', 'group', 'form']);
});
it('should emit status change events in the right order', () => {
c.statusChanges.subscribe(() => logger.push('control'));
g.statusChanges.subscribe(() => logger.push('group'));
form.statusChanges.subscribe(() => logger.push('form'));
g.disable();
expect(logger).toEqual(['control', 'group', 'form']);
});
it('should not emit value change events when called with `emitEvent: false`', () => {
c.valueChanges.subscribe(() => logger.push('control'));
g.valueChanges.subscribe(() => logger.push('group'));
form.valueChanges.subscribe(() => logger.push('form'));
g.disable({emitEvent: false});
expect(logger).toEqual([]);
g.enable({emitEvent: false});
expect(logger).toEqual([]);
});
it('should not emit status change events when called with `emitEvent: false`', () => {
c.statusChanges.subscribe(() => logger.push('control'));
g.statusChanges.subscribe(() => logger.push('group'));
form.statusChanges.subscribe(() => logger.push('form'));
g.disable({emitEvent: false});
expect(logger).toEqual([]);
g.enable({emitEvent: false});
expect(logger).toEqual([]);
});
});
}); | {
"end_byte": 71867,
"start_byte": 62489,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_71873_74794 | describe('updateTreeValidity()', () => {
let c: FormControl, c2: FormControl, c3: FormControl;
let nested: FormGroup, form: FormGroup;
let logger: string[];
beforeEach(() => {
c = new FormControl('one');
c2 = new FormControl('two');
c3 = new FormControl('three');
nested = new FormGroup({one: c, two: c2});
form = new FormGroup({nested: nested, three: c3});
logger = [];
c.statusChanges.subscribe(() => logger.push('one'));
c2.statusChanges.subscribe(() => logger.push('two'));
c3.statusChanges.subscribe(() => logger.push('three'));
nested.statusChanges.subscribe(() => logger.push('nested'));
form.statusChanges.subscribe(() => logger.push('form'));
});
it('should update tree validity', () => {
(form as any)._updateTreeValidity();
expect(logger).toEqual(['one', 'two', 'nested', 'three', 'form']);
});
it('should not emit events when called with `emitEvent: false`', () => {
(form as any)._updateTreeValidity({emitEvent: false});
expect(logger).toEqual([]);
});
});
describe('setControl()', () => {
let c: FormControl;
let g: FormGroup;
beforeEach(() => {
c = new FormControl('one');
g = new FormGroup({one: c});
});
it('should replace existing control with new control', () => {
const c2 = new FormControl('new!', Validators.minLength(10));
g.setControl('one', c2);
expect(g.controls['one']).toEqual(c2);
expect(g.value).toEqual({one: 'new!'});
expect(g.valid).toBe(false);
});
it('should add control if control did not exist before', () => {
const c2 = new FormControl('new!', Validators.minLength(10));
g.setControl('two', c2);
expect(g.controls['two']).toEqual(c2);
expect(g.value).toEqual({one: 'one', two: 'new!'});
expect(g.valid).toBe(false);
});
it('should remove control if new control is null', () => {
g.setControl('one', null!);
expect(g.controls['one']).not.toBeDefined();
expect(g.value).toEqual({});
});
it('should only emit value change event once', () => {
const logger: string[] = [];
const c2 = new FormControl('new!');
g.valueChanges.subscribe(() => logger.push('change!'));
g.setControl('one', c2);
expect(logger).toEqual(['change!']);
});
it('should not emit event called when `FormGroup.setControl` with `emitEvent: false`', () => {
const logger: string[] = [];
const c2 = new FormControl('new!');
g.valueChanges.subscribe(() => logger.push('value change'));
g.statusChanges.subscribe(() => logger.push('status change'));
g.setControl('one', c2, {emitEvent: false});
expect(logger).toEqual([]);
});
}); | {
"end_byte": 74794,
"start_byte": 71873,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_74800_82454 | describe('emit `statusChanges` and `valueChanges` with/without async/sync validators', () => {
const attachEventsLogger = (
control: AbstractControl,
log: string[],
controlName?: string,
) => {
const name = controlName ? ` (${controlName})` : '';
control.statusChanges.subscribe((status) => log.push(`status${name}: ${status}`));
control.valueChanges.subscribe((value) =>
log.push(`value${name}: ${JSON.stringify(value)}`),
);
};
describe('stand alone controls', () => {
it('should run the async validator on stand alone controls and set status to `INVALID`', fakeAsync(() => {
const logs: string[] = [];
const c = new FormControl('', null, simpleAsyncValidator({timeout: 0, shouldFail: true}));
attachEventsLogger(c, logs);
expect(logs.length).toBe(0);
tick(1);
c.setValue('new!', {emitEvent: true});
tick(1);
// Note that above `simpleAsyncValidator` is called with `timeout:0`. When the timeout
// is set to `0`, the function returns `of(error)`, and the function behaves in a
// synchronous manner. Because of this there is no `PENDING` state as seen in the
// `logs`.
expect(logs).toEqual([
'status: INVALID', // status change emitted as a result of initial async validator run
'value: "new!"', // value change emitted by `setValue`
'status: INVALID', // async validator run after `setValue` call
]);
}));
it('should run the async validator on stand alone controls and set status to `VALID`', fakeAsync(() => {
const logs: string[] = [];
const c = new FormControl('', null, asyncValidator('new!'));
attachEventsLogger(c, logs);
expect(logs.length).toBe(0);
tick(1);
c.setValue('new!', {emitEvent: true});
tick(1);
expect(logs).toEqual([
'status: INVALID', // status change emitted as a result of initial async validator run
'value: "new!"', // value change emitted by `setValue`
'status: PENDING', // status change emitted by `setValue`
'status: VALID', // async validator run after `setValue` call
]);
}));
it('should run the async validator on stand alone controls, include `PENDING` and set status to `INVALID`', fakeAsync(() => {
const logs: string[] = [];
const c = new FormControl('', null, simpleAsyncValidator({timeout: 1, shouldFail: true}));
attachEventsLogger(c, logs);
expect(logs.length).toBe(0);
tick(1);
c.setValue('new!', {emitEvent: true});
tick(1);
expect(logs).toEqual([
'status: INVALID', // status change emitted as a result of initial async validator run
'value: "new!"', // value change emitted by `setValue`
'status: PENDING', // status change emitted by `setValue`
'status: INVALID', // async validator run after `setValue` call
]);
}));
it('should run setValue before the initial async validator and set status to `VALID`', fakeAsync(() => {
const logs: string[] = [];
const c = new FormControl('', null, asyncValidator('new!'));
attachEventsLogger(c, logs);
expect(logs.length).toBe(0);
c.setValue('new!', {emitEvent: true});
tick(1);
// The `setValue` call invoked synchronously cancels the initial run of the
// `asyncValidator` (which would cause the control status to be changed to `INVALID`), so
// the log contains only events after calling `setValue`.
expect(logs).toEqual([
'value: "new!"', // value change emitted by `setValue`
'status: PENDING', // status change emitted by `setValue`
'status: VALID', // async validator run after `setValue` call
]);
}));
it('should run setValue before the initial async validator and set status to `INVALID`', fakeAsync(() => {
const logs: string[] = [];
const c = new FormControl('', null, simpleAsyncValidator({timeout: 1, shouldFail: true}));
attachEventsLogger(c, logs);
expect(logs.length).toBe(0);
c.setValue('new!', {emitEvent: true});
tick(1);
// The `setValue` call invoked synchronously cancels the initial run of the
// `asyncValidator` (which would cause the control status to be changed to `INVALID`), so
// the log contains only events after calling `setValue`.
expect(logs).toEqual([
'value: "new!"', // value change emitted by `setValue`
'status: PENDING', // status change emitted by `setValue`
'status: INVALID', // async validator run after `setValue` call
]);
}));
it('should cancel initial run of the async validator and not emit anything', fakeAsync(() => {
const logger: string[] = [];
const c = new FormControl('', null, simpleAsyncValidator({timeout: 1, shouldFail: true}));
attachEventsLogger(c, logger);
expect(logger.length).toBe(0);
c.setValue('new!', {emitEvent: false});
tick(1);
// Because we are calling `setValue` with `emitEvent: false`, nothing is emitted
// and our logger remains empty
expect(logger).toEqual([]);
}));
it('should cancel initial run of the async validator and emit on the event Observable', fakeAsync(() => {
const c = new FormControl('', null, simpleAsyncValidator({timeout: 1, shouldFail: true}));
const events: ControlEvent[] = [];
c.events.subscribe((e) => events.push(e));
expect(events.length).toBe(0);
c.setValue('new!');
tick(1);
// validator was invoked twice (init + setValue)
// but since we cancel pending validators we only get 1 status update cycle
expect(events[0]).toBeInstanceOf(ValueChangeEvent);
expect(events[1]).toBeInstanceOf(StatusChangeEvent);
expect((events[1] as StatusChangeEvent).status).toBe('PENDING');
expect(events[2]).toBeInstanceOf(StatusChangeEvent);
expect((events[2] as StatusChangeEvent).status).toBe('INVALID');
}));
it('should run the sync validator on stand alone controls and set status to `INVALID`', fakeAsync(() => {
const logs: string[] = [];
const c = new FormControl('new!', Validators.required);
attachEventsLogger(c, logs);
expect(logs.length).toBe(0);
tick(1);
c.setValue('', {emitEvent: true});
tick(1);
expect(logs).toEqual([
'value: ""', // value change emitted by `setValue`
'status: INVALID', // status change emitted by `setValue`
]);
}));
it('should run the sync validator on stand alone controls and set status to `VALID`', fakeAsync(() => {
const logs: string[] = [];
const c = new FormControl('', Validators.required);
attachEventsLogger(c, logs);
expect(logs.length).toBe(0);
tick(1);
c.setValue('new!', {emitEvent: true});
tick(1);
expect(logs).toEqual([
'value: "new!"', // value change emitted by `setValue`
'status: VALID', // status change emitted by `setValue`
]);
}));
}); | {
"end_byte": 82454,
"start_byte": 74800,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_82462_90519 | describe('combination of multiple form controls', () => {
it('should run the async validator on the FormControl added to the FormGroup and set status to `VALID`', fakeAsync(() => {
const logs: string[] = [];
const c1 = new FormControl('one');
const g1 = new FormGroup({'one': c1});
// Initial state of the controls
expect(currentStateOf([c1, g1])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Control 1
{errors: null, pending: false, status: 'VALID'}, // Group
]);
attachEventsLogger(g1, logs, 'g1');
const c2 = new FormControl('new!', null, asyncValidator('new!'));
attachEventsLogger(c2, logs, 'c2');
// Initial state of the new control
expect(currentStateOf([c2])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Control 2
]);
expect(logs.length).toBe(0);
g1.setControl('one', c2);
tick(1);
expect(logs).toEqual([
'value (g1): {"one":"new!"}', // value change emitted by `setControl`
'status (g1): PENDING', // value change emitted by `setControl`
'status (c2): VALID', // async validator run after `setControl` call
'status (g1): VALID', // status changed from the `setControl` call
]);
// Final state of all controls
expect(currentStateOf([g1, c2])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Group
{errors: null, pending: false, status: 'VALID'}, // Control 2
]);
}));
it('should run the async validator on the FormControl added to the FormGroup and set status to `INVALID`', fakeAsync(() => {
const logs: string[] = [];
const c1 = new FormControl('one');
const g1 = new FormGroup({'one': c1});
// Initial state of the controls
expect(currentStateOf([c1, g1])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Control 1
{errors: null, pending: false, status: 'VALID'}, // Group
]);
attachEventsLogger(g1, logs, 'g1');
const c2 = new FormControl(
'new!',
null,
simpleAsyncValidator({timeout: 1, shouldFail: true}),
);
attachEventsLogger(c2, logs, 'c2');
// Initial state of the new control
expect(currentStateOf([c2])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Control 2
]);
expect(logs.length).toBe(0);
g1.setControl('one', c2);
tick(1);
expect(logs).toEqual([
'value (g1): {"one":"new!"}',
'status (g1): PENDING', // g1 async validator is invoked after `g1.setControl` call
'status (c2): INVALID', // c2 async validator trigger at c2 init, completed with the
// `INVALID` status
'status (g1): INVALID', // g1 validator completed with the `INVALID` status
]);
// Final state of all controls
expect(currentStateOf([g1, c2])).toEqual([
{errors: null, pending: false, status: 'INVALID'}, // Group
{errors: {async: true}, pending: false, status: 'INVALID'}, // Control 2
]);
}));
it('should run the async validator at `FormControl` and `FormGroup` level and set status to `INVALID`', fakeAsync(() => {
const logs: string[] = [];
const c1 = new FormControl('one');
const g1 = new FormGroup(
{'one': c1},
null,
simpleAsyncValidator({timeout: 1, shouldFail: true}),
);
// Initial state of the controls
expect(currentStateOf([c1, g1])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Control 1
{errors: null, pending: true, status: 'PENDING'}, // Group
]);
attachEventsLogger(g1, logs, 'g1');
const c2 = new FormControl(
'new!',
null,
simpleAsyncValidator({timeout: 1, shouldFail: true}),
);
attachEventsLogger(c2, logs, 'c2');
// Initial state of the new control
expect(currentStateOf([c2])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Control 2
]);
expect(logs.length).toBe(0);
g1.setControl('one', c2);
tick(1);
expect(logs).toEqual([
'value (g1): {"one":"new!"}',
'status (g1): PENDING', // g1 async validator is invoked after `g1.setControl` call
'status (c2): INVALID', // c2 async validator trigger at c2 init, completed with the
// `INVALID` status
'status (g1): PENDING', // c2 update triggered g1 to re-run validation
'status (g1): INVALID', // g1 validator completed with the `INVALID` status
]);
// Final state of all controls
expect(currentStateOf([g1, c2])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group
{errors: {async: true}, pending: false, status: 'INVALID'}, // Control 2
]);
}));
it('should run the async validator on a `FormArray` and a `FormControl` and status to `INVALID`', fakeAsync(() => {
const logs: string[] = [];
const c1 = new FormControl('one');
const g1 = new FormGroup(
{'one': c1},
null,
simpleAsyncValidator({timeout: 1, shouldFail: true}),
);
const fa = new FormArray(
[g1],
null!,
simpleAsyncValidator({timeout: 1, shouldFail: true}),
);
attachEventsLogger(g1, logs, 'g1');
// Initial state of the controls
expect(currentStateOf([c1, g1, fa])).toEqual([
{errors: null, pending: false, status: 'VALID'}, // Control 1
{errors: null, pending: true, status: 'PENDING'}, // Group
{errors: null, pending: true, status: 'PENDING'}, // FormArray
]);
attachEventsLogger(fa, logs, 'fa');
const c2 = new FormControl(
'new!',
null,
simpleAsyncValidator({timeout: 1, shouldFail: true}),
);
attachEventsLogger(c2, logs, 'c2');
// Initial state of the new control
expect(currentStateOf([c2])).toEqual([
{errors: null, pending: true, status: 'PENDING'}, // Control 2
]);
expect(logs.length).toBe(0);
g1.setControl('one', c2);
tick(1);
expect(logs).toEqual([
'value (g1): {"one":"new!"}', // g1's call to `setControl` triggered value update
'status (g1): PENDING', // g1's call to `setControl` triggered status update
'value (fa): [{"one":"new!"}]', // g1 update triggers the `FormArray` value update
'status (fa): PENDING', // g1 update triggers the `FormArray` status update
'status (c2): INVALID', // async validator run after `setControl` call
'status (g1): PENDING', // async validator run after `setControl` call
'status (fa): PENDING', // async validator run after `setControl` call
'status (g1): INVALID', // g1 validator completed with the `INVALID` status
'status (fa): PENDING', // fa validator still running
'status (fa): INVALID', // fa validator completed with the `INVALID` status
]);
// Final state of all controls
expect(currentStateOf([g1, fa, c2])).toEqual([
{errors: {async: true}, pending: false, status: 'INVALID'}, // Group
{errors: {async: true}, pending: false, status: 'INVALID'}, // FormArray
{errors: {async: true}, pending: false, status: 'INVALID'}, // Control 2
]);
}));
});
}); | {
"end_byte": 90519,
"start_byte": 82462,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/form_group_spec.ts_90525_93414 | describe('pending', () => {
let c: FormControl;
let g: FormGroup;
beforeEach(() => {
c = new FormControl('value');
g = new FormGroup({'one': c});
});
it('should be false after creating a control', () => {
expect(g.pending).toEqual(false);
});
it('should be true after changing the value of the control', () => {
c.markAsPending();
expect(g.pending).toEqual(true);
});
it('should not update the parent when onlySelf = true', () => {
c.markAsPending({onlySelf: true});
expect(g.pending).toEqual(false);
});
describe('status change events', () => {
let logger: string[];
beforeEach(() => {
logger = [];
g.statusChanges.subscribe((status) => logger.push(status));
});
it('should emit event after marking control as pending', () => {
c.markAsPending();
expect(logger).toEqual(['PENDING']);
});
it('should not emit event when onlySelf = true', () => {
c.markAsPending({onlySelf: true});
expect(logger).toEqual([]);
});
it('should not emit event when called with `emitEvent: false`', () => {
c.markAsPending({emitEvent: false});
expect(logger).toEqual([]);
});
it('should emit event when parent is markedAsPending', () => {
g.markAsPending();
expect(logger).toEqual(['PENDING']);
});
});
});
describe('can be extended', () => {
it('by a group with string keys', () => {
abstract class StringKeyGroup extends FormGroup {
override registerControl(name: string, value: AbstractControl): AbstractControl {
return new FormControl('');
}
}
});
it('by a group with generic keys', () => {
abstract class SpecialGroup<T extends {[key: string]: AbstractControl}> extends FormGroup {
override registerControl<K extends keyof T>(
name: K,
value: AbstractControl,
): AbstractControl {
return new FormControl('');
}
}
});
it('by a group with unconstrained generic keys', () => {
abstract class SpecialGroup<T> extends FormGroup {
override registerControl<K extends keyof T>(
name: K,
value: AbstractControl,
): AbstractControl {
return new FormControl('');
}
}
});
});
it('should throw with invalid keys', () => {
const consoleWarnSpy = spyOn(console, 'warn');
new FormGroup({
foo: new FormControl('foo'),
bar: new FormControl('foo', [Validators.required]),
'baz.not.ok': new FormControl('baz'),
});
expect(consoleWarnSpy).toHaveBeenCalledTimes(1);
});
});
})(); | {
"end_byte": 93414,
"start_byte": 90525,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_group_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_0_1369 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, ɵgetDOM as getDOM} from '@angular/common';
import {Component, Directive, ElementRef, forwardRef, Input, Type, ViewChild} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed, tick, waitForAsync} from '@angular/core/testing';
import {
AbstractControl,
AsyncValidator,
COMPOSITION_BUFFER_MODE,
ControlValueAccessor,
FormControl,
FormsModule,
MaxValidator,
MinValidator,
NG_ASYNC_VALIDATORS,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
NgForm,
NgModel,
Validator,
} from '@angular/forms';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {dispatchEvent, sortedClassList} from '@angular/platform-browser/testing/src/browser_util';
import {merge} from 'rxjs';
import {NgModelCustomComp, NgModelCustomWrapper} from './value_accessor_integration_spec';
describe('template-driven forms integration tests', () => {
function initTest<T>(component: Type<T>, ...directives: Type<any>[]): ComponentFixture<T> {
TestBed.configureTestingModule({
declarations: [component, ...directives],
imports: [FormsModule, CommonModule],
});
return TestBed.createComponent(component);
}
| {
"end_byte": 1369,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_1373_10711 | escribe('basic functionality', () => {
it('should support ngModel for standalone fields', fakeAsync(() => {
const fixture = initTest(StandaloneNgModel);
fixture.componentInstance.name = 'oldValue';
fixture.detectChanges();
tick();
// model -> view
const input = fixture.debugElement.query(By.css('input')).nativeElement;
expect(input.value).toEqual('oldValue');
input.value = 'updatedValue';
dispatchEvent(input, 'input');
tick();
// view -> model
expect(fixture.componentInstance.name).toEqual('updatedValue');
}));
it('should support ngModel registration with a parent form', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Nancy';
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.value).toEqual({name: 'Nancy'});
expect(form.valid).toBe(false);
}));
it('should report properties which are written outside of template bindings', async () => {
// For example ngModel writes to `checked` property programmatically
// (template does not contain binding to `checked` explicitly)
// https://github.com/angular/angular/issues/33695
@Component({
selector: 'app-root',
template: `<input type="radio" value="one" [(ngModel)]="active"/>`,
standalone: false,
})
class AppComponent {
active = 'one';
}
TestBed.configureTestingModule({imports: [FormsModule], declarations: [AppComponent]});
const fixture = TestBed.createComponent(AppComponent);
// We need the Await as `ngModel` writes data asynchronously into the DOM
await fixture.detectChanges();
const input = fixture.debugElement.query(By.css('input'));
expect(input.properties['checked']).toBe(true);
expect(input.nativeElement.checked).toBe(true);
});
it('should add novalidate by default to form element', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.detectChanges();
tick();
const form = fixture.debugElement.query(By.css('form'));
expect(form.nativeElement.getAttribute('novalidate')).toEqual('');
}));
it('should be possible to use native validation and angular forms', fakeAsync(() => {
const fixture = initTest(NgModelNativeValidateForm);
fixture.detectChanges();
tick();
const form = fixture.debugElement.query(By.css('form'));
expect(form.nativeElement.hasAttribute('novalidate')).toEqual(false);
}));
it('should support ngModelGroup', fakeAsync(() => {
const fixture = initTest(NgModelGroupForm);
fixture.componentInstance.first = 'Nancy';
fixture.componentInstance.last = 'Drew';
fixture.componentInstance.email = 'some email';
fixture.detectChanges();
tick();
// model -> view
const inputs = fixture.debugElement.queryAll(By.css('input'));
expect(inputs[0].nativeElement.value).toEqual('Nancy');
expect(inputs[1].nativeElement.value).toEqual('Drew');
inputs[0].nativeElement.value = 'Carson';
dispatchEvent(inputs[0].nativeElement, 'input');
tick();
// view -> model
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.value).toEqual({name: {first: 'Carson', last: 'Drew'}, email: 'some email'});
}));
it('should add controls and control groups to form control model', fakeAsync(() => {
const fixture = initTest(NgModelGroupForm);
fixture.componentInstance.first = 'Nancy';
fixture.componentInstance.last = 'Drew';
fixture.componentInstance.email = 'some email';
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.control.get('name')!.value).toEqual({first: 'Nancy', last: 'Drew'});
expect(form.control.get('name.first')!.value).toEqual('Nancy');
expect(form.control.get('email')!.value).toEqual('some email');
}));
it('should remove controls and control groups from form control model', fakeAsync(() => {
const fixture = initTest(NgModelNgIfForm);
fixture.componentInstance.emailShowing = true;
fixture.componentInstance.first = 'Nancy';
fixture.componentInstance.email = 'some email';
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.control.get('email')!.value).toEqual('some email');
expect(form.value).toEqual({name: {first: 'Nancy'}, email: 'some email'});
// should remove individual control successfully
fixture.componentInstance.emailShowing = false;
fixture.detectChanges();
tick();
expect(form.control.get('email')).toBe(null);
expect(form.value).toEqual({name: {first: 'Nancy'}});
expect(form.control.get('name')!.value).toEqual({first: 'Nancy'});
expect(form.control.get('name.first')!.value).toEqual('Nancy');
// should remove form group successfully
fixture.componentInstance.groupShowing = false;
fixture.detectChanges();
tick();
expect(form.control.get('name')).toBe(null);
expect(form.control.get('name.first')).toBe(null);
expect(form.value).toEqual({});
}));
it('should set status classes with ngModel', waitForAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'aa';
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(sortedClassList(input)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']);
input.value = 'updatedValue';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(sortedClassList(formEl)).toEqual([
'ng-dirty',
'ng-submitted',
'ng-touched',
'ng-valid',
]);
expect(sortedClassList(input)).not.toContain('ng-submitted');
dispatchEvent(formEl, 'reset');
fixture.detectChanges();
expect(sortedClassList(formEl)).toEqual(['ng-pristine', 'ng-untouched', 'ng-valid']);
expect(sortedClassList(input)).not.toContain('ng-submitted');
});
}));
it('should set status classes with ngModel and async validators', fakeAsync(() => {
const fixture = initTest(NgModelAsyncValidation, NgAsyncValidator);
fixture.whenStable().then(() => {
fixture.detectChanges();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
expect(sortedClassList(input)).toEqual(['ng-pending', 'ng-pristine', 'ng-untouched']);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(sortedClassList(input)).toEqual(['ng-pending', 'ng-pristine', 'ng-touched']);
input.value = 'updatedValue';
dispatchEvent(input, 'input');
tick();
fixture.detectChanges();
expect(sortedClassList(input)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']);
});
}));
it('should set status classes with ngModelGroup and ngForm', waitForAsync(() => {
const fixture = initTest(NgModelGroupForm);
fixture.componentInstance.first = '';
fixture.detectChanges();
const form = fixture.debugElement.query(By.css('form')).nativeElement;
const modelGroup = fixture.debugElement.query(By.css('[ngModelGroup]')).nativeElement;
const input = fixture.debugElement.query(By.css('input')).nativeElement;
// ngModelGroup creates its control asynchronously
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(sortedClassList(modelGroup)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']);
expect(sortedClassList(form)).toEqual(['ng-invalid', 'ng-pristine', 'ng-untouched']);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(sortedClassList(modelGroup)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']);
expect(sortedClassList(form)).toEqual(['ng-invalid', 'ng-pristine', 'ng-touched']);
input.value = 'updatedValue';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(sortedClassList(modelGroup)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']);
expect(sortedClassList(form)).toEqual(['ng-dirty', 'ng-touched', 'ng-valid']);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(sortedClassList(formEl)).toEqual([
'ng-dirty',
'ng-submitted',
'ng-touched',
'ng-valid',
]);
});
}));
| {
"end_byte": 10711,
"start_byte": 1373,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_10717_17770 | t('should set status classes involving nested FormGroups', async () => {
const fixture = initTest(NgModelNestedForm);
fixture.componentInstance.first = '';
fixture.componentInstance.other = '';
fixture.detectChanges();
const form = fixture.debugElement.query(By.css('form')).nativeElement;
const modelGroup = fixture.debugElement.query(By.css('[ngModelGroup]')).nativeElement;
const input = fixture.debugElement.query(By.css('input')).nativeElement;
await fixture.whenStable();
fixture.detectChanges();
expect(sortedClassList(modelGroup)).toEqual(['ng-pristine', 'ng-untouched', 'ng-valid']);
expect(sortedClassList(form)).toEqual(['ng-pristine', 'ng-untouched', 'ng-valid']);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(sortedClassList(modelGroup)).toEqual(['ng-pristine', 'ng-untouched', 'ng-valid']);
expect(sortedClassList(form)).toEqual([
'ng-pristine',
'ng-submitted',
'ng-untouched',
'ng-valid',
]);
expect(sortedClassList(input)).not.toContain('ng-submitted');
dispatchEvent(formEl, 'reset');
fixture.detectChanges();
expect(sortedClassList(modelGroup)).toEqual(['ng-pristine', 'ng-untouched', 'ng-valid']);
expect(sortedClassList(form)).toEqual(['ng-pristine', 'ng-untouched', 'ng-valid']);
expect(sortedClassList(input)).not.toContain('ng-submitted');
});
it('should not create a template-driven form when ngNoForm is used', () => {
const fixture = initTest(NgNoFormComp);
fixture.detectChanges();
expect(fixture.debugElement.children[0].providerTokens!.length).toEqual(0);
});
it('should not add novalidate when ngNoForm is used', () => {
const fixture = initTest(NgNoFormComp);
fixture.detectChanges();
const form = fixture.debugElement.query(By.css('form'));
expect(form.nativeElement.hasAttribute('novalidate')).toEqual(false);
});
it('should keep track of the ngModel value when together used with an ngFor inside a form', fakeAsync(() => {
@Component({
template: `
<form>
<div *ngFor="let item of items; index as i">
<input [(ngModel)]="item.value" name="name-{{i}}">
</div>
</form>
`,
standalone: false,
})
class App {
private _counter = 0;
items: {value: string}[] = [];
add(amount: number) {
for (let i = 0; i < amount; i++) {
this.items.push({value: `${this._counter++}`});
}
}
remove(index: number) {
this.items.splice(index, 1);
}
}
const getValues = () =>
fixture.debugElement.queryAll(By.css('input')).map((el) => el.nativeElement.value);
const fixture = initTest(App);
fixture.componentInstance.add(3);
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '1', '2']);
fixture.componentInstance.remove(1);
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '2']);
fixture.componentInstance.add(1);
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '2', '3']);
fixture.componentInstance.items[1].value = '1';
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '1', '3']);
fixture.componentInstance.items[2].value = '2';
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '1', '2']);
}));
it('should keep track of the ngModel value when together used with an ngFor inside an ngModelGroup', fakeAsync(() => {
@Component({
template: `
<form>
<ng-container ngModelGroup="group">
<div *ngFor="let item of items; index as i">
<input [(ngModel)]="item.value" name="name-{{i}}">
</div>
</ng-container>
</form>
`,
standalone: false,
})
class App {
private _counter = 0;
group = {};
items: {value: string}[] = [];
add(amount: number) {
for (let i = 0; i < amount; i++) {
this.items.push({value: `${this._counter++}`});
}
}
remove(index: number) {
this.items.splice(index, 1);
}
}
const getValues = () =>
fixture.debugElement.queryAll(By.css('input')).map((el) => el.nativeElement.value);
const fixture = initTest(App);
fixture.componentInstance.add(3);
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '1', '2']);
fixture.componentInstance.remove(1);
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '2']);
fixture.componentInstance.add(1);
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '2', '3']);
fixture.componentInstance.items[1].value = '1';
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '1', '3']);
fixture.componentInstance.items[2].value = '2';
fixture.detectChanges();
tick();
expect(getValues()).toEqual(['0', '1', '2']);
}));
});
describe('name and ngModelOptions', () => {
it('should throw if ngModel has a parent form but no name attr or standalone label', () => {
const fixture = initTest(InvalidNgModelNoName);
expect(() => fixture.detectChanges()).toThrowError(new RegExp(`name attribute must be set`));
});
it('should not throw if ngModel has a parent form, no name attr, and a standalone label', () => {
const fixture = initTest(NgModelOptionsStandalone);
expect(() => fixture.detectChanges()).not.toThrow();
});
it('should not register standalone ngModels with parent form', fakeAsync(() => {
const fixture = initTest(NgModelOptionsStandalone);
fixture.componentInstance.one = 'some data';
fixture.componentInstance.two = 'should not show';
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const inputs = fixture.debugElement.queryAll(By.css('input'));
tick();
expect(form.value).toEqual({one: 'some data'});
expect(inputs[1].nativeElement.value).toEqual('should not show');
}));
it('should override name attribute with ngModelOptions name if provided', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.options = {name: 'override'};
fixture.componentInstance.name = 'some data';
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.value).toEqual({override: 'some data'});
}));
});
describe('updateOn', () => {
| {
"end_byte": 17770,
"start_byte": 10717,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_17775_27991 | escribe('blur', () => {
it('should default updateOn to change', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {};
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const name = form.control.get('name') as FormControl;
expect((name as any)._updateOn).toBeUndefined();
expect(name.updateOn).toEqual('change');
}));
it('should set control updateOn to blur properly', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const name = form.control.get('name') as FormControl;
expect((name as any)._updateOn).toEqual('blur');
expect(name.updateOn).toEqual('blur');
}));
it('should always set value and validity on init', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Nancy Drew';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(input.value)
.withContext('Expected initial view value to be set.')
.toEqual('Nancy Drew');
expect(form.value).withContext('Expected initial control value be set.').toEqual({
name: 'Nancy Drew',
});
expect(form.valid).withContext('Expected validation to run on initial value.').toBe(true);
}));
it('should always set value programmatically right away', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Nancy Drew';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
fixture.componentInstance.name = 'Carson';
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(input.value)
.withContext('Expected view value to update on programmatic change.')
.toEqual('Carson');
expect(form.value).toEqual(
{name: 'Carson'},
'Expected form value to update on programmatic change.',
);
expect(form.valid)
.withContext('Expected validation to run immediately on programmatic change.')
.toBe(false);
}));
it('should update value/validity on blur', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Carson';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(fixture.componentInstance.name)
.withContext('Expected value not to update on input.')
.toEqual('Carson');
expect(form.valid).withContext('Expected validation not to run on input.').toBe(false);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(fixture.componentInstance.name)
.withContext('Expected value to update on blur.')
.toEqual('Nancy Drew');
expect(form.valid).withContext('Expected validation to run on blur.').toBe(true);
}));
it('should wait for second blur to update value/validity again', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Carson';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
dispatchEvent(input, 'blur');
fixture.detectChanges();
input.value = 'Carson';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(fixture.componentInstance.name)
.withContext('Expected value not to update until another blur.')
.toEqual('Nancy Drew');
expect(form.valid)
.withContext('Expected validation not to run until another blur.')
.toBe(true);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(fixture.componentInstance.name)
.withContext('Expected value to update on second blur.')
.toEqual('Carson');
expect(form.valid).withContext('Expected validation to run on second blur.').toBe(false);
}));
it('should not update dirtiness until blur', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.dirty).withContext('Expected dirtiness not to update on input.').toBe(false);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(form.dirty).withContext('Expected dirtiness to update on blur.').toBe(true);
}));
it('should not update touched until blur', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.touched).withContext('Expected touched not to update on input.').toBe(false);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(form.touched).withContext('Expected touched to update on blur.').toBe(true);
}));
it('should not emit valueChanges or statusChanges until blur', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const values: any[] = [];
const form = fixture.debugElement.children[0].injector.get(NgForm);
const sub = merge(form.valueChanges!, form.statusChanges!).subscribe((val) =>
values.push(val),
);
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
expect(values)
.withContext('Expected no valueChanges or statusChanges on input.')
.toEqual([]);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(values).toEqual(
[{name: 'Nancy Drew'}, 'VALID'],
'Expected valueChanges and statusChanges on blur.',
);
sub.unsubscribe();
}));
it('should not fire ngModelChange event on blur unless value has changed', fakeAsync(() => {
const fixture = initTest(NgModelChangesForm);
fixture.componentInstance.name = 'Carson';
fixture.componentInstance.options = {updateOn: 'blur'};
fixture.detectChanges();
tick();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges not to fire.')
.toEqual([]);
const input = fixture.debugElement.query(By.css('input')).nativeElement;
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges not to fire if value unchanged.')
.toEqual([]);
input.value = 'Carson';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges not to fire on input.')
.toEqual([]);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges to fire once blurred if value changed.')
.toEqual(['fired']);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(fixture.componentInstance.events).toEqual(
['fired'],
'Expected ngModelChanges not to fire again on blur unless value changed.',
);
input.value = 'Bess';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges not to fire on input after blur.')
.toEqual(['fired']);
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(fixture.componentInstance.events).toEqual(
['fired', 'fired'],
'Expected ngModelChanges to fire again on blur if value changed.',
);
}));
});
| {
"end_byte": 27991,
"start_byte": 17775,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_27997_36398 | escribe('submit', () => {
it('should set control updateOn to submit properly', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const name = form.control.get('name') as FormControl;
expect((name as any)._updateOn).toEqual('submit');
expect(name.updateOn).toEqual('submit');
}));
it('should always set value and validity on init', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Nancy Drew';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(input.value)
.withContext('Expected initial view value to be set.')
.toEqual('Nancy Drew');
expect(form.value)
.withContext('Expected initial control value be set.')
.toEqual({name: 'Nancy Drew'});
expect(form.valid).withContext('Expected validation to run on initial value.').toBe(true);
}));
it('should always set value programmatically right away', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Nancy Drew';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
fixture.componentInstance.name = 'Carson';
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(input.value)
.withContext('Expected view value to update on programmatic change.')
.toEqual('Carson');
expect(form.value)
.withContext('Expected form value to update on programmatic change.')
.toEqual({name: 'Carson'});
expect(form.valid)
.withContext('Expected validation to run immediately on programmatic change.')
.toBe(false);
}));
it('should update on submit', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Carson';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(fixture.componentInstance.name)
.withContext('Expected value not to update on input.')
.toEqual('Carson');
expect(form.valid).withContext('Expected validation not to run on input.').toBe(false);
dispatchEvent(input, 'blur');
fixture.detectChanges();
tick();
expect(fixture.componentInstance.name)
.withContext('Expected value not to update on blur.')
.toEqual('Carson');
expect(form.valid).withContext('Expected validation not to run on blur.').toBe(false);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(fixture.componentInstance.name)
.withContext('Expected value to update on submit.')
.toEqual('Nancy Drew');
expect(form.valid).withContext('Expected validation to run on submit.').toBe(true);
}));
it('should wait until second submit to update again', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Carson';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
tick();
input.value = 'Carson';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(fixture.componentInstance.name)
.withContext('Expected value not to update until second submit.')
.toEqual('Nancy Drew');
expect(form.valid)
.withContext('Expected validation not to run until second submit.')
.toBe(true);
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
tick();
expect(fixture.componentInstance.name)
.withContext('Expected value to update on second submit.')
.toEqual('Carson');
expect(form.valid).withContext('Expected validation to run on second submit.').toBe(false);
}));
it('should not run validation for onChange controls on submit', fakeAsync(() => {
const validatorSpy = jasmine.createSpy('validator');
const groupValidatorSpy = jasmine.createSpy('groupValidatorSpy');
const fixture = initTest(NgModelGroupForm);
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
form.control.get('name')!.setValidators(groupValidatorSpy);
form.control.get('name.last')!.setValidators(validatorSpy);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(validatorSpy).not.toHaveBeenCalled();
expect(groupValidatorSpy).not.toHaveBeenCalled();
}));
it('should not update dirtiness until submit', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.dirty).withContext('Expected dirtiness not to update on input.').toBe(false);
dispatchEvent(input, 'blur');
fixture.detectChanges();
tick();
expect(form.dirty).withContext('Expected dirtiness not to update on blur.').toBe(false);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(form.dirty).withContext('Expected dirtiness to update on submit.').toBe(true);
}));
it('should not update touched until submit', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
dispatchEvent(input, 'blur');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.touched).withContext('Expected touched not to update on blur.').toBe(false);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(form.touched).withContext('Expected touched to update on submit.').toBe(true);
}));
| {
"end_byte": 36398,
"start_byte": 27997,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_36406_42178 | t('should reset properly', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'Nancy' as string | null;
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
dispatchEvent(input, 'blur');
fixture.detectChanges();
const form = fixture.debugElement.children[0].injector.get(NgForm);
form.resetForm();
fixture.detectChanges();
tick();
expect(input.value).withContext('Expected view value to reset.').toEqual('');
expect(form.value).withContext('Expected form value to reset.').toEqual({name: null});
expect(fixture.componentInstance.name)
.withContext('Expected ngModel value to reset.')
.toEqual(null);
expect(form.dirty).withContext('Expected dirty to stay false on reset.').toBe(false);
expect(form.touched).withContext('Expected touched to stay false on reset.').toBe(false);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(form.value).withContext('Expected form value to stay empty on submit').toEqual({
name: null,
});
expect(fixture.componentInstance.name)
.withContext('Expected ngModel value to stay empty on submit.')
.toEqual(null);
expect(form.dirty).withContext('Expected dirty to stay false on submit.').toBe(false);
expect(form.touched).withContext('Expected touched to stay false on submit.').toBe(false);
}));
it('should not emit valueChanges or statusChanges until submit', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = '';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const values: any[] = [];
const form = fixture.debugElement.children[0].injector.get(NgForm);
const sub = merge(form.valueChanges!, form.statusChanges!).subscribe((val) =>
values.push(val),
);
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
expect(values)
.withContext('Expected no valueChanges or statusChanges on input.')
.toEqual([]);
dispatchEvent(input, 'blur');
fixture.detectChanges();
tick();
expect(values)
.withContext('Expected no valueChanges or statusChanges on blur.')
.toEqual([]);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(values).toEqual(
[{name: 'Nancy Drew'}, 'VALID'],
'Expected valueChanges and statusChanges on submit.',
);
sub.unsubscribe();
}));
it('should not fire ngModelChange event on submit unless value has changed', fakeAsync(() => {
const fixture = initTest(NgModelChangesForm);
fixture.componentInstance.name = 'Carson';
fixture.componentInstance.options = {updateOn: 'submit'};
fixture.detectChanges();
tick();
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges not to fire if value unchanged.')
.toEqual([]);
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Carson';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges not to fire on input.')
.toEqual([]);
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges to fire once submitted if value changed.')
.toEqual(['fired']);
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(fixture.componentInstance.events).toEqual(
['fired'],
'Expected ngModelChanges not to fire again on submit unless value changed.',
);
input.value = 'Bess';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
expect(fixture.componentInstance.events)
.withContext('Expected ngModelChanges not to fire on input after submit.')
.toEqual(['fired']);
dispatchEvent(formEl, 'submit');
fixture.detectChanges();
expect(fixture.componentInstance.events).toEqual(
['fired', 'fired'],
'Expected ngModelChanges to fire again on submit if value changed.',
);
}));
it('should not prevent the default action on forms with method="dialog"', fakeAsync(() => {
if (typeof HTMLDialogElement === 'undefined') {
return;
}
const fixture = initTest(NativeDialogForm);
fixture.detectChanges();
tick();
const event = dispatchEvent(fixture.componentInstance.form.nativeElement, 'submit');
fixture.detectChanges();
expect(event.defaultPrevented).toBe(false);
}));
});
| {
"end_byte": 42178,
"start_byte": 36406,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_42184_49857 | escribe('ngFormOptions', () => {
it('should use ngFormOptions value when ngModelOptions are not set', fakeAsync(() => {
const fixture = initTest(NgModelOptionsStandalone);
fixture.componentInstance.options = {name: 'two'};
fixture.componentInstance.formOptions = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const controlOne = form.control.get('one')! as FormControl;
expect((controlOne as any)._updateOn).toBeUndefined();
expect(controlOne.updateOn)
.withContext('Expected first control to inherit updateOn from parent form.')
.toEqual('blur');
const controlTwo = form.control.get('two')! as FormControl;
expect((controlTwo as any)._updateOn).toBeUndefined();
expect(controlTwo.updateOn)
.withContext('Expected last control to inherit updateOn from parent form.')
.toEqual('blur');
}));
it('should actually update using ngFormOptions value', fakeAsync(() => {
const fixture = initTest(NgModelOptionsStandalone);
fixture.componentInstance.one = '';
fixture.componentInstance.formOptions = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'Nancy Drew';
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.value).withContext('Expected value not to update on input.').toEqual({
one: '',
});
dispatchEvent(input, 'blur');
fixture.detectChanges();
expect(form.value).withContext('Expected value to update on blur.').toEqual({
one: 'Nancy Drew',
});
}));
it('should allow ngModelOptions updateOn to override ngFormOptions', fakeAsync(() => {
const fixture = initTest(NgModelOptionsStandalone);
fixture.componentInstance.options = {updateOn: 'blur', name: 'two'};
fixture.componentInstance.formOptions = {updateOn: 'change'};
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const controlOne = form.control.get('one')! as FormControl;
expect((controlOne as any)._updateOn).toBeUndefined();
expect(controlOne.updateOn)
.withContext('Expected control updateOn to inherit form updateOn.')
.toEqual('change');
const controlTwo = form.control.get('two')! as FormControl;
expect((controlTwo as any)._updateOn)
.withContext('Expected control to set blur override.')
.toEqual('blur');
expect(controlTwo.updateOn)
.withContext('Expected control updateOn to override form updateOn.')
.toEqual('blur');
}));
it('should update using ngModelOptions override', fakeAsync(() => {
const fixture = initTest(NgModelOptionsStandalone);
fixture.componentInstance.one = '';
fixture.componentInstance.two = '';
fixture.componentInstance.options = {updateOn: 'blur', name: 'two'};
fixture.componentInstance.formOptions = {updateOn: 'change'};
fixture.detectChanges();
tick();
const [inputOne, inputTwo] = fixture.debugElement.queryAll(By.css('input'));
inputOne.nativeElement.value = 'Nancy Drew';
dispatchEvent(inputOne.nativeElement, 'input');
fixture.detectChanges();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.value).withContext('Expected first value to update on input.').toEqual({
one: 'Nancy Drew',
two: '',
});
inputTwo.nativeElement.value = 'Carson Drew';
dispatchEvent(inputTwo.nativeElement, 'input');
fixture.detectChanges();
tick();
expect(form.value).withContext('Expected second value not to update on input.').toEqual({
one: 'Nancy Drew',
two: '',
});
dispatchEvent(inputTwo.nativeElement, 'blur');
fixture.detectChanges();
expect(form.value).toEqual(
{one: 'Nancy Drew', two: 'Carson Drew'},
'Expected second value to update on blur.',
);
}));
it('should not use ngFormOptions for standalone ngModels', fakeAsync(() => {
const fixture = initTest(NgModelOptionsStandalone);
fixture.componentInstance.two = '';
fixture.componentInstance.options = {standalone: true};
fixture.componentInstance.formOptions = {updateOn: 'blur'};
fixture.detectChanges();
tick();
const inputTwo = fixture.debugElement.queryAll(By.css('input'))[1].nativeElement;
inputTwo.value = 'Nancy Drew';
dispatchEvent(inputTwo, 'input');
fixture.detectChanges();
expect(fixture.componentInstance.two)
.withContext('Expected standalone ngModel not to inherit blur update.')
.toEqual('Nancy Drew');
}));
});
});
describe('submit and reset events', () => {
it('should emit ngSubmit event with the original submit event on submit', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.event = null!;
const form = fixture.debugElement.query(By.css('form'));
dispatchEvent(form.nativeElement, 'submit');
tick();
expect(fixture.componentInstance.event.type).toEqual('submit');
}));
it('should mark NgForm as submitted on submit event', fakeAsync(() => {
const fixture = initTest(NgModelForm);
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.submitted).toBe(false);
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
dispatchEvent(formEl, 'submit');
tick();
expect(form.submitted).toBe(true);
}));
it('should reset the form to empty when reset event is fired', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.componentInstance.name = 'should be cleared' as string | null;
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const formEl = fixture.debugElement.query(By.css('form'));
const input = fixture.debugElement.query(By.css('input'));
expect(input.nativeElement.value).toBe('should be cleared'); // view value
expect(fixture.componentInstance.name).toBe('should be cleared'); // ngModel value
expect(form.value.name).toEqual('should be cleared'); // control value
dispatchEvent(formEl.nativeElement, 'reset');
fixture.detectChanges();
tick();
expect(input.nativeElement.value).toBe(''); // view value
expect(fixture.componentInstance.name).toBe(null); // ngModel value
expect(form.value.name).toEqual(null); // control value
}));
it('should reset the form submit state when reset button is clicked', fakeAsync(() => {
const fixture = initTest(NgModelForm);
const form = fixture.debugElement.children[0].injector.get(NgForm);
const formEl = fixture.debugElement.query(By.css('form'));
dispatchEvent(formEl.nativeElement, 'submit');
fixture.detectChanges();
tick();
expect(form.submitted).toBe(true);
dispatchEvent(formEl.nativeElement, 'reset');
fixture.detectChanges();
tick();
expect(form.submitted).toBe(false);
}));
});
| {
"end_byte": 49857,
"start_byte": 42184,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_49861_55060 | escribe('valueChange and statusChange events', () => {
it('should emit valueChanges and statusChanges on init', fakeAsync(() => {
const fixture = initTest(NgModelForm);
const form = fixture.debugElement.children[0].injector.get(NgForm);
fixture.componentInstance.name = 'aa';
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.value).toEqual({});
let formValidity: string = undefined!;
let formValue: Object = undefined!;
form.statusChanges!.subscribe((status: string) => (formValidity = status));
form.valueChanges!.subscribe((value: string) => (formValue = value));
tick();
expect(formValidity).toEqual('INVALID');
expect(formValue).toEqual({name: 'aa'});
}));
it('should mark controls dirty before emitting the value change event', fakeAsync(() => {
const fixture = initTest(NgModelForm);
const form = fixture.debugElement.children[0].injector.get(NgForm).form;
fixture.detectChanges();
tick();
form.get('name')!.valueChanges.subscribe(() => {
expect(form.get('name')!.dirty).toBe(true);
});
const inputEl = fixture.debugElement.query(By.css('input')).nativeElement;
inputEl.value = 'newValue';
dispatchEvent(inputEl, 'input');
}));
it('should mark controls pristine before emitting the value change event when resetting ', fakeAsync(() => {
const fixture = initTest(NgModelForm);
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm).form;
const formEl = fixture.debugElement.query(By.css('form')).nativeElement;
const inputEl = fixture.debugElement.query(By.css('input')).nativeElement;
inputEl.value = 'newValue';
dispatchEvent(inputEl, 'input');
expect(form.get('name')!.pristine).toBe(false);
form.get('name')!.valueChanges.subscribe(() => {
expect(form.get('name')!.pristine).toBe(true);
});
dispatchEvent(formEl, 'reset');
}));
});
describe('disabled controls', () => {
it('should not consider disabled controls in value or validation', fakeAsync(() => {
const fixture = initTest(NgModelGroupForm);
fixture.componentInstance.isDisabled = false;
fixture.componentInstance.first = '';
fixture.componentInstance.last = 'Drew';
fixture.componentInstance.email = 'some email';
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.value).toEqual({name: {first: '', last: 'Drew'}, email: 'some email'});
expect(form.valid).toBe(false);
expect(form.control.get('name.first')!.disabled).toBe(false);
fixture.componentInstance.isDisabled = true;
fixture.detectChanges();
tick();
expect(form.value).toEqual({name: {last: 'Drew'}, email: 'some email'});
expect(form.valid).toBe(true);
expect(form.control.get('name.first')!.disabled).toBe(true);
}));
it('should add disabled attribute in the UI if disable() is called programmatically', fakeAsync(() => {
const fixture = initTest(NgModelGroupForm);
fixture.componentInstance.isDisabled = false;
fixture.componentInstance.first = 'Nancy';
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
form.control.get('name.first')!.disable();
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css(`[name="first"]`));
expect(input.nativeElement.disabled).toBe(true);
}));
it('should disable a custom control if disabled attr is added', waitForAsync(() => {
const fixture = initTest(NgModelCustomWrapper, NgModelCustomComp);
fixture.componentInstance.name = 'Nancy';
fixture.componentInstance.isDisabled = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.control.get('name')!.disabled).toBe(true);
const customInput = fixture.debugElement.query(By.css('[name="custom"]'));
expect(customInput.nativeElement.disabled).toEqual(true);
});
});
}));
it('should disable a control with unbound disabled attr', fakeAsync(() => {
TestBed.overrideComponent(NgModelForm, {
set: {
template: `
<form>
<input name="name" [(ngModel)]="name" disabled>
</form>
`,
},
});
const fixture = initTest(NgModelForm);
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.control.get('name')!.disabled).toBe(true);
const input = fixture.debugElement.query(By.css('input'));
expect(input.nativeElement.disabled).toEqual(true);
form.control.enable();
fixture.detectChanges();
tick();
expect(input.nativeElement.disabled).toEqual(false);
}));
});
| {
"end_byte": 55060,
"start_byte": 49861,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_55064_62333 | escribe('validation directives', () => {
it('required validator should validate checkbox', fakeAsync(() => {
const fixture = initTest(NgModelCheckboxRequiredValidator);
fixture.detectChanges();
tick();
const control = fixture.debugElement.children[0].injector
.get(NgForm)
.control.get('checkbox')!;
const input = fixture.debugElement.query(By.css('input'));
expect(input.nativeElement.checked).toBe(false);
expect(control.hasError('required')).toBe(false);
fixture.componentInstance.required = true;
fixture.detectChanges();
tick();
expect(input.nativeElement.checked).toBe(false);
expect(control.hasError('required')).toBe(true);
input.nativeElement.checked = true;
dispatchEvent(input.nativeElement, 'change');
fixture.detectChanges();
tick();
expect(input.nativeElement.checked).toBe(true);
expect(control.hasError('required')).toBe(false);
input.nativeElement.checked = false;
dispatchEvent(input.nativeElement, 'change');
fixture.detectChanges();
tick();
expect(input.nativeElement.checked).toBe(false);
expect(control.hasError('required')).toBe(true);
fixture.componentInstance.required = false;
dispatchEvent(input.nativeElement, 'change');
fixture.detectChanges();
tick();
expect(input.nativeElement.checked).toBe(false);
expect(control.hasError('required')).toBe(false);
}));
it('should validate email', fakeAsync(() => {
const fixture = initTest(NgModelEmailValidator);
fixture.detectChanges();
tick();
const control = fixture.debugElement.children[0].injector.get(NgForm).control.get('email')!;
const input = fixture.debugElement.query(By.css('input'));
expect(control.hasError('email')).toBe(false);
fixture.componentInstance.validatorEnabled = true;
fixture.detectChanges();
tick();
expect(input.nativeElement.value).toEqual('');
expect(control.hasError('email')).toBe(false);
input.nativeElement.value = '@';
dispatchEvent(input.nativeElement, 'input');
tick();
expect(input.nativeElement.value).toEqual('@');
expect(control.hasError('email')).toBe(true);
input.nativeElement.value = 'test@gmail.com';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
tick();
expect(input.nativeElement.value).toEqual('test@gmail.com');
expect(control.hasError('email')).toBe(false);
input.nativeElement.value = 'text';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
tick();
expect(input.nativeElement.value).toEqual('text');
expect(control.hasError('email')).toBe(true);
}));
it('should support dir validators using bindings', fakeAsync(() => {
const fixture = initTest(NgModelValidationBindings);
fixture.componentInstance.required = true;
fixture.componentInstance.minLen = 3;
fixture.componentInstance.maxLen = 3;
fixture.componentInstance.pattern = '.{3,}';
fixture.detectChanges();
tick();
const required = fixture.debugElement.query(By.css('[name=required]'));
const minLength = fixture.debugElement.query(By.css('[name=minlength]'));
const maxLength = fixture.debugElement.query(By.css('[name=maxlength]'));
const pattern = fixture.debugElement.query(By.css('[name=pattern]'));
required.nativeElement.value = '';
minLength.nativeElement.value = '1';
maxLength.nativeElement.value = '1234';
pattern.nativeElement.value = '12';
dispatchEvent(required.nativeElement, 'input');
dispatchEvent(minLength.nativeElement, 'input');
dispatchEvent(maxLength.nativeElement, 'input');
dispatchEvent(pattern.nativeElement, 'input');
fixture.detectChanges();
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.control.hasError('required', ['required'])).toEqual(true);
expect(form.control.hasError('minlength', ['minlength'])).toEqual(true);
expect(form.control.hasError('maxlength', ['maxlength'])).toEqual(true);
expect(form.control.hasError('pattern', ['pattern'])).toEqual(true);
required.nativeElement.value = '1';
minLength.nativeElement.value = '123';
maxLength.nativeElement.value = '123';
pattern.nativeElement.value = '123';
dispatchEvent(required.nativeElement, 'input');
dispatchEvent(minLength.nativeElement, 'input');
dispatchEvent(maxLength.nativeElement, 'input');
dispatchEvent(pattern.nativeElement, 'input');
expect(form.valid).toEqual(true);
}));
it('should support optional fields with string pattern validator', fakeAsync(() => {
const fixture = initTest(NgModelMultipleValidators);
fixture.componentInstance.required = false;
fixture.componentInstance.pattern = '[a-z]+';
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value = '';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
expect(form.valid).toBeTruthy();
input.nativeElement.value = '1';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
expect(form.valid).toBeFalsy();
expect(form.control.hasError('pattern', ['tovalidate'])).toBeTruthy();
}));
it('should support optional fields with RegExp pattern validator', fakeAsync(() => {
const fixture = initTest(NgModelMultipleValidators);
fixture.componentInstance.required = false;
fixture.componentInstance.pattern = /^[a-z]+$/;
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value = '';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
expect(form.valid).toBeTruthy();
input.nativeElement.value = '1';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
expect(form.valid).toBeFalsy();
expect(form.control.hasError('pattern', ['tovalidate'])).toBeTruthy();
}));
it('should support optional fields with minlength validator', fakeAsync(() => {
const fixture = initTest(NgModelMultipleValidators);
fixture.componentInstance.required = false;
fixture.componentInstance.minLen = 2;
fixture.detectChanges();
tick();
const form = fixture.debugElement.children[0].injector.get(NgForm);
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value = '';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
expect(form.valid).toBeTruthy();
input.nativeElement.value = '1';
dispatchEvent(input.nativeElement, 'input');
fixture.detectChanges();
expect(form.valid).toBeFalsy();
expect(form.control.hasError('minlength', ['tovalidate'])).toBeTruthy();
}));
| {
"end_byte": 62333,
"start_byte": 55064,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_62339_71487 | t('changes on bound properties should change the validation state of the form', fakeAsync(() => {
const fixture = initTest(NgModelValidationBindings);
fixture.detectChanges();
tick();
const required = fixture.debugElement.query(By.css('[name=required]'));
const minLength = fixture.debugElement.query(By.css('[name=minlength]'));
const maxLength = fixture.debugElement.query(By.css('[name=maxlength]'));
const pattern = fixture.debugElement.query(By.css('[name=pattern]'));
required.nativeElement.value = '';
minLength.nativeElement.value = '1';
maxLength.nativeElement.value = '1234';
pattern.nativeElement.value = '12';
dispatchEvent(required.nativeElement, 'input');
dispatchEvent(minLength.nativeElement, 'input');
dispatchEvent(maxLength.nativeElement, 'input');
dispatchEvent(pattern.nativeElement, 'input');
const form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.control.hasError('required', ['required'])).toEqual(false);
expect(form.control.hasError('minlength', ['minlength'])).toEqual(false);
expect(form.control.hasError('maxlength', ['maxlength'])).toEqual(false);
expect(form.control.hasError('pattern', ['pattern'])).toEqual(false);
expect(form.valid).toEqual(true);
fixture.componentInstance.required = true;
fixture.componentInstance.minLen = 3;
fixture.componentInstance.maxLen = 3;
fixture.componentInstance.pattern = '.{3,}';
fixture.detectChanges();
dispatchEvent(required.nativeElement, 'input');
dispatchEvent(minLength.nativeElement, 'input');
dispatchEvent(maxLength.nativeElement, 'input');
dispatchEvent(pattern.nativeElement, 'input');
expect(form.control.hasError('required', ['required'])).toEqual(true);
expect(form.control.hasError('minlength', ['minlength'])).toEqual(true);
expect(form.control.hasError('maxlength', ['maxlength'])).toEqual(true);
expect(form.control.hasError('pattern', ['pattern'])).toEqual(true);
expect(form.valid).toEqual(false);
expect(required.nativeElement.getAttribute('required')).toEqual('');
expect(fixture.componentInstance.minLen.toString()).toEqual(
minLength.nativeElement.getAttribute('minlength'),
);
expect(fixture.componentInstance.maxLen.toString()).toEqual(
maxLength.nativeElement.getAttribute('maxlength'),
);
expect(fixture.componentInstance.pattern.toString()).toEqual(
pattern.nativeElement.getAttribute('pattern'),
);
fixture.componentInstance.required = false;
fixture.componentInstance.minLen = null!;
fixture.componentInstance.maxLen = null!;
fixture.componentInstance.pattern = null!;
fixture.detectChanges();
expect(form.control.hasError('required', ['required'])).toEqual(false);
expect(form.control.hasError('minlength', ['minlength'])).toEqual(false);
expect(form.control.hasError('maxlength', ['maxlength'])).toEqual(false);
expect(form.control.hasError('pattern', ['pattern'])).toEqual(false);
expect(form.valid).toEqual(true);
expect(required.nativeElement.getAttribute('required')).toEqual(null);
expect(required.nativeElement.getAttribute('minlength')).toEqual(null);
expect(required.nativeElement.getAttribute('maxlength')).toEqual(null);
expect(required.nativeElement.getAttribute('pattern')).toEqual(null);
}));
it('should update control status', fakeAsync(() => {
const fixture = initTest(NgModelChangeState);
const inputEl = fixture.debugElement.query(By.css('input'));
const inputNativeEl = inputEl.nativeElement;
const onNgModelChange = jasmine.createSpy('onNgModelChange');
fixture.componentInstance.onNgModelChange = onNgModelChange;
fixture.detectChanges();
tick();
expect(onNgModelChange).not.toHaveBeenCalled();
inputNativeEl.value = 'updated';
onNgModelChange.and.callFake((ngModel: NgModel) => {
expect(ngModel.invalid).toBe(true);
expect(ngModel.value).toBe('updated');
});
dispatchEvent(inputNativeEl, 'input');
expect(onNgModelChange).toHaveBeenCalled();
tick();
inputNativeEl.value = '333';
onNgModelChange.and.callFake((ngModel: NgModel) => {
expect(ngModel.invalid).toBe(false);
expect(ngModel.value).toBe('333');
});
dispatchEvent(inputNativeEl, 'input');
expect(onNgModelChange).toHaveBeenCalledTimes(2);
tick();
}));
it('should validate max', fakeAsync(() => {
const fixture = initTest(NgModelMaxValidator);
fixture.componentInstance.max = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(input.getAttribute('max')).toEqual('10');
expect(form.valid).toEqual(true);
expect(form.controls['max'].errors).toBeNull();
input.value = 11;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['max'].errors).toEqual({max: {max: 10, actual: 11}});
input.value = 9;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['max'].errors).toBeNull();
fixture.componentInstance.max = 0;
fixture.detectChanges();
tick();
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(input.getAttribute('max')).toEqual('0');
expect(form.valid).toEqual(false);
expect(form.controls['max'].errors).toEqual({max: {max: 0, actual: 9}});
input.value = 0;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['max'].errors).toBeNull();
}));
it('should validate max for float number', fakeAsync(() => {
const fixture = initTest(NgModelMaxValidator);
fixture.componentInstance.max = 10.25;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(input.getAttribute('max')).toEqual('10.25');
expect(form.valid).toEqual(true);
expect(form.controls['max'].errors).toBeNull();
input.value = 10.25;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['max'].errors).toBeNull();
input.value = 10.15;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['max'].errors).toBeNull();
input.value = 10.35;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['max'].errors).toEqual({max: {max: 10.25, actual: 10.35}});
}));
it('should apply max validation when control value is defined as a string', fakeAsync(() => {
const fixture = initTest(NgModelMaxValidator);
fixture.componentInstance.max = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '11';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(input.getAttribute('max')).toEqual('10');
expect(form.valid).toEqual(false);
expect(form.controls['max'].errors).toEqual({max: {max: 10, actual: 11}});
input.value = '9';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['max'].errors).toBeNull();
}));
it('should re-validate if max changes', fakeAsync(() => {
const fixture = initTest(NgModelMaxValidator);
fixture.componentInstance.max = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = 11;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['max'].errors).toEqual({max: {max: 10, actual: 11}});
input.value = 9;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['max'].errors).toBeNull();
fixture.componentInstance.max = 5;
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['max'].errors).toEqual({max: {max: 5, actual: 9}});
}));
| {
"end_byte": 71487,
"start_byte": 62339,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_71493_79188 | t('should validate min', fakeAsync(() => {
const fixture = initTest(NgModelMinValidator);
fixture.componentInstance.min = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(input.getAttribute('min')).toEqual('10');
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
input.value = 11;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
input.value = 9;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min'].errors).toEqual({min: {min: 10, actual: 9}});
fixture.componentInstance.min = 0;
fixture.detectChanges();
tick();
input.value = -5;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(input.getAttribute('min')).toEqual('0');
expect(form.valid).toEqual(false);
expect(form.controls['min'].errors).toEqual({min: {min: 0, actual: -5}});
input.value = 0;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
}));
it('should validate min for float number', fakeAsync(() => {
const fixture = initTest(NgModelMinValidator);
fixture.componentInstance.min = 10.25;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(input.getAttribute('min')).toEqual('10.25');
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
input.value = 10.35;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
input.value = 10.25;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
input.value = 10.15;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min'].errors).toEqual({min: {min: 10.25, actual: 10.15}});
}));
it('should apply min validation when control value is defined as a string', fakeAsync(() => {
const fixture = initTest(NgModelMinValidator);
fixture.componentInstance.min = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '11';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(input.getAttribute('min')).toEqual('10');
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
input.value = '9';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min'].errors).toEqual({min: {min: 10, actual: 9}});
}));
it('should re-validate if min changes', fakeAsync(() => {
const fixture = initTest(NgModelMinValidator);
fixture.componentInstance.min = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = 11;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
input.value = 9;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min'].errors).toEqual({min: {min: 10, actual: 9}});
fixture.componentInstance.min = 9;
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min'].errors).toBeNull();
}));
it('should not include the min and max validators when using another directive with the same properties', fakeAsync(() => {
const fixture = initTest(NgModelNoMinMaxValidator);
const validateFnSpy = spyOn(MaxValidator.prototype, 'validate');
fixture.componentInstance.min = 10;
fixture.componentInstance.max = 20;
fixture.detectChanges();
tick();
const min = fixture.debugElement.query(By.directive(MinValidator));
expect(min).toBeNull();
const max = fixture.debugElement.query(By.directive(MaxValidator));
expect(max).toBeNull();
const cd = fixture.debugElement.query(By.directive(CustomDirective));
expect(cd).toBeDefined();
expect(validateFnSpy).not.toHaveBeenCalled();
}));
it('should not include the min and max validators when using a custom component with the same properties', fakeAsync(() => {
@Directive({
selector: 'my-custom-component',
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => MyCustomComponentDirective),
},
],
standalone: false,
})
class MyCustomComponentDirective implements ControlValueAccessor {
@Input() min!: number;
@Input() max!: number;
writeValue(obj: any): void {}
registerOnChange(fn: any): void {}
registerOnTouched(fn: any): void {}
}
@Component({
template: `
<!-- no min/max validators should be matched on these elements -->
<my-custom-component name="min" ngModel [min]="min"></my-custom-component>
<my-custom-component name="max" ngModel [max]="max"></my-custom-component>
`,
standalone: false,
})
class AppComponent {}
const fixture = initTest(AppComponent, MyCustomComponentDirective);
const validateFnSpy = spyOn(MaxValidator.prototype, 'validate');
fixture.detectChanges();
tick();
const mv = fixture.debugElement.query(By.directive(MaxValidator));
expect(mv).toBeNull();
const cd = fixture.debugElement.query(By.directive(CustomDirective));
expect(cd).toBeDefined();
expect(validateFnSpy).not.toHaveBeenCalled();
}));
it('should not include the min and max validators for inputs with type range', fakeAsync(() => {
@Component({
template: '<input type="range" min="10" max="20">',
standalone: false,
})
class AppComponent {}
const fixture = initTest(AppComponent);
const maxValidateFnSpy = spyOn(MaxValidator.prototype, 'validate');
const minValidateFnSpy = spyOn(MinValidator.prototype, 'validate');
fixture.detectChanges();
tick();
const maxValidator = fixture.debugElement.query(By.directive(MaxValidator));
expect(maxValidator).toBeNull();
const minValidator = fixture.debugElement.query(By.directive(MinValidator));
expect(minValidator).toBeNull();
expect(maxValidateFnSpy).not.toHaveBeenCalled();
expect(minValidateFnSpy).not.toHaveBeenCalled();
}));
| {
"end_byte": 79188,
"start_byte": 71493,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_79194_87761 | escribe('enabling validators conditionally', () => {
it('should not include the minLength and maxLength validators for null', fakeAsync(() => {
@Component({
template:
'<form><input name="amount" ngModel [minlength]="minlen" [maxlength]="maxlen"></form>',
standalone: false,
})
class MinLengthMaxLengthComponent {
minlen: number | null = null;
maxlen: number | null = null;
control!: FormControl;
}
const fixture = initTest(MinLengthMaxLengthComponent);
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
const control = fixture.debugElement.children[0].injector
.get(NgForm)
.control.get('amount')!;
interface minmax {
minlength: number | null;
maxlength: number | null;
}
interface state {
isValid: boolean;
failedValidator?: string;
}
const setInputValue = (value: number) => {
input.value = value;
dispatchEvent(input, 'input');
fixture.detectChanges();
};
const verifyValidatorAttrValues = (values: {minlength: any; maxlength: any}) => {
expect(input.getAttribute('minlength')).toBe(values.minlength);
expect(input.getAttribute('maxlength')).toBe(values.maxlength);
};
const setValidatorValues = (values: minmax) => {
fixture.componentInstance.minlen = values.minlength;
fixture.componentInstance.maxlen = values.maxlength;
fixture.detectChanges();
};
const verifyFormState = (state: state) => {
expect(form.valid).toBe(state.isValid);
if (state.failedValidator) {
expect(control!.hasError('minlength')).toEqual(state.failedValidator === 'minlength');
expect(control!.hasError('maxlength')).toEqual(state.failedValidator === 'maxlength');
}
};
////////// Actual test scenarios start below //////////
// 1. Verify that validators are disabled when input is `null`.
verifyValidatorAttrValues({minlength: null, maxlength: null});
verifyValidatorAttrValues({minlength: null, maxlength: null});
// 2. Verify that setting validator inputs (to a value different from `null`) activate
// validators.
setInputValue(12345);
setValidatorValues({minlength: 2, maxlength: 4});
verifyValidatorAttrValues({minlength: '2', maxlength: '4'});
verifyFormState({isValid: false, failedValidator: 'maxlength'});
// 3. Changing value to the valid range should make the form valid.
setInputValue(123);
verifyFormState({isValid: true});
// 4. Changing value to trigger `minlength` validator.
setInputValue(1);
verifyFormState({isValid: false, failedValidator: 'minlength'});
// 5. Changing validator inputs to verify that attribute values are updated (and the
// form is now valid).
setInputValue(1);
setValidatorValues({minlength: 1, maxlength: 5});
verifyValidatorAttrValues({minlength: '1', maxlength: '5'});
verifyFormState({isValid: true});
// 6. Reset validator inputs back to `null` should deactivate validators.
setInputValue(123);
setValidatorValues({minlength: null, maxlength: null});
verifyValidatorAttrValues({minlength: null, maxlength: null});
verifyFormState({isValid: true});
}));
it('should not include the min and max validators for null', fakeAsync(() => {
@Component({
template:
'<form><input type="number" name="minmaxinput" ngModel [min]="minlen" [max]="maxlen"></form>',
standalone: false,
})
class MinLengthMaxLengthComponent {
minlen: number | null = null;
maxlen: number | null = null;
control!: FormControl;
}
const fixture = initTest(MinLengthMaxLengthComponent);
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
const control = fixture.debugElement.children[0].injector
.get(NgForm)
.control.get('minmaxinput')!;
interface minmax {
min: number | null;
max: number | null;
}
interface state {
isValid: boolean;
failedValidator?: string;
}
const setInputValue = (value: number) => {
input.value = value;
dispatchEvent(input, 'input');
fixture.detectChanges();
};
const verifyValidatorAttrValues = (values: {min: any; max: any}) => {
expect(input.getAttribute('min')).toBe(values.min);
expect(input.getAttribute('max')).toBe(values.max);
};
const setValidatorValues = (values: minmax) => {
fixture.componentInstance.minlen = values.min;
fixture.componentInstance.maxlen = values.max;
fixture.detectChanges();
};
const verifyFormState = (state: state) => {
expect(form.valid).toBe(state.isValid);
if (state.failedValidator) {
expect(control!.hasError('min')).toEqual(state.failedValidator === 'min');
expect(control!.hasError('max')).toEqual(state.failedValidator === 'max');
}
};
////////// Actual test scenarios start below //////////
// 1. Verify that validators are disabled when input is `null`.
verifyValidatorAttrValues({min: null, max: null});
verifyValidatorAttrValues({min: null, max: null});
// 2. Verify that setting validator inputs (to a value different from `null`) activate
// validators.
setInputValue(12345);
setValidatorValues({min: 2, max: 4});
verifyValidatorAttrValues({min: '2', max: '4'});
verifyFormState({isValid: false, failedValidator: 'max'});
// 3. Changing value to the valid range should make the form valid.
setInputValue(3);
verifyFormState({isValid: true});
// 4. Changing value to trigger `minlength` validator.
setInputValue(1);
verifyFormState({isValid: false, failedValidator: 'min'});
// 5. Changing validator inputs to verify that attribute values are updated (and the
// form is now valid).
setInputValue(1);
setValidatorValues({min: 1, max: 5});
verifyValidatorAttrValues({min: '1', max: '5'});
verifyFormState({isValid: true});
// 6. Reset validator inputs back to `null` should deactivate validators.
setInputValue(123);
setValidatorValues({min: null, max: null});
verifyValidatorAttrValues({min: null, max: null});
verifyFormState({isValid: true});
}));
});
['number', 'string'].forEach((inputType: string) => {
it(`should validate min and max when constraints are represented using a ${inputType}`, fakeAsync(() => {
const fixture = initTest(NgModelMinMaxValidator);
fixture.componentInstance.min = inputType === 'string' ? '5' : 5;
fixture.componentInstance.max = inputType === 'string' ? '10' : 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
input.value = 11;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min_max'].errors).toEqual({max: {max: 10, actual: 11}});
input.value = 4;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min_max'].errors).toEqual({min: {min: 5, actual: 4}});
input.value = 9;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
}));
});
| {
"end_byte": 87761,
"start_byte": 79194,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_87766_96375 | t('should validate min and max', fakeAsync(() => {
const fixture = initTest(NgModelMinMaxValidator);
fixture.componentInstance.min = 5;
fixture.componentInstance.max = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
input.value = 11;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min_max'].errors).toEqual({max: {max: 10, actual: 11}});
input.value = 4;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min_max'].errors).toEqual({min: {min: 5, actual: 4}});
input.value = 9;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
}));
it('should apply min and max validation when control value is defined as a string', fakeAsync(() => {
const fixture = initTest(NgModelMinMaxValidator);
fixture.componentInstance.min = 5;
fixture.componentInstance.max = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
input.value = '11';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min_max'].errors).toEqual({max: {max: 10, actual: 11}});
input.value = '4';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min_max'].errors).toEqual({min: {min: 5, actual: 4}});
input.value = '9';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
}));
it('should re-validate if min/max changes', fakeAsync(() => {
const fixture = initTest(NgModelMinMaxValidator);
fixture.componentInstance.min = 5;
fixture.componentInstance.max = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = 10;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
input.value = 12;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min_max'].errors).toEqual({max: {max: 10, actual: 12}});
fixture.componentInstance.max = 12;
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
input.value = 5;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
input.value = 0;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(false);
expect(form.controls['min_max'].errors).toEqual({min: {min: 5, actual: 0}});
fixture.componentInstance.min = 0;
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
}));
it('should run min/max validation for empty values ', fakeAsync(() => {
const fixture = initTest(NgModelMinMaxValidator);
fixture.componentInstance.min = 5;
fixture.componentInstance.max = 10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
const maxValidateFnSpy = spyOn(MaxValidator.prototype, 'validate');
const minValidateFnSpy = spyOn(MinValidator.prototype, 'validate');
input.value = '';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toEqual(true);
expect(form.controls['min_max'].errors).toBeNull();
expect(maxValidateFnSpy).toHaveBeenCalled();
expect(minValidateFnSpy).toHaveBeenCalled();
}));
it('should run min/max validation for negative values', fakeAsync(() => {
const fixture = initTest(NgModelMinMaxValidator);
fixture.componentInstance.min = -20;
fixture.componentInstance.max = -10;
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
const form = fixture.debugElement.children[0].injector.get(NgForm);
input.value = '-30';
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toBeFalse();
expect(form.controls['min_max'].errors).toEqual({min: {min: -20, actual: -30}});
input.value = -15;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toBeTruthy();
expect(form.controls['min_max'].errors).toBeNull();
input.value = -5;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toBeFalse();
expect(form.controls['min_max'].errors).toEqual({max: {max: -10, actual: -5}});
input.value = 0;
dispatchEvent(input, 'input');
fixture.detectChanges();
expect(form.valid).toBeFalse();
expect(form.controls['min_max'].errors).toEqual({max: {max: -10, actual: 0}});
}));
it('should call registerOnValidatorChange as a part of a formGroup setup', fakeAsync(() => {
let registerOnValidatorChangeFired = 0;
let registerOnAsyncValidatorChangeFired = 0;
@Directive({
selector: '[ng-noop-validator]',
providers: [
{provide: NG_VALIDATORS, useExisting: forwardRef(() => NoOpValidator), multi: true},
],
standalone: false,
})
class NoOpValidator implements Validator {
@Input() validatorInput = '';
validate(c: AbstractControl) {
return null;
}
public registerOnValidatorChange(fn: () => void) {
registerOnValidatorChangeFired++;
}
}
@Directive({
selector: '[ng-noop-async-validator]',
providers: [
{
provide: NG_ASYNC_VALIDATORS,
useExisting: forwardRef(() => NoOpAsyncValidator),
multi: true,
},
],
standalone: false,
})
class NoOpAsyncValidator implements AsyncValidator {
@Input() validatorInput = '';
validate(c: AbstractControl) {
return Promise.resolve(null);
}
public registerOnValidatorChange(fn: () => void) {
registerOnAsyncValidatorChangeFired++;
}
}
@Component({
selector: 'ng-model-noop-validation',
template: `
<form>
<div ngModelGroup="emptyGroup" ng-noop-validator ng-noop-async-validator [validatorInput]="validatorInput">
<input name="fgInput" ngModel>
</div>
</form>
`,
standalone: false,
})
class NgModelNoOpValidation {
validatorInput = 'foo';
emptyGroup = {};
}
const fixture = initTest(NgModelNoOpValidation, NoOpValidator, NoOpAsyncValidator);
fixture.detectChanges();
tick();
expect(registerOnValidatorChangeFired).toBe(1);
expect(registerOnAsyncValidatorChangeFired).toBe(1);
fixture.componentInstance.validatorInput = 'bar';
fixture.detectChanges();
// Changing validator inputs should not cause `registerOnValidatorChange` to be invoked,
// since it's invoked just once during the setup phase.
expect(registerOnValidatorChangeFired).toBe(1);
expect(registerOnAsyncValidatorChangeFired).toBe(1);
}));
});
| {
"end_byte": 96375,
"start_byte": 87766,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_96379_104640 | escribe('IME events', () => {
it('should determine IME event handling depending on platform by default', fakeAsync(() => {
const fixture = initTest(StandaloneNgModel);
const inputEl = fixture.debugElement.query(By.css('input'));
const inputNativeEl = inputEl.nativeElement;
fixture.componentInstance.name = 'oldValue';
fixture.detectChanges();
tick();
expect(inputNativeEl.value).toEqual('oldValue');
inputEl.triggerEventHandler('compositionstart');
inputNativeEl.value = 'updatedValue';
dispatchEvent(inputNativeEl, 'input');
tick();
const isAndroid = /android (\d+)/.test(getDOM().getUserAgent().toLowerCase());
if (isAndroid) {
// On Android, values should update immediately
expect(fixture.componentInstance.name).toEqual('updatedValue');
} else {
// On other platforms, values should wait until compositionend
expect(fixture.componentInstance.name).toEqual('oldValue');
inputEl.triggerEventHandler('compositionend', {target: {value: 'updatedValue'}});
fixture.detectChanges();
tick();
expect(fixture.componentInstance.name).toEqual('updatedValue');
}
}));
it('should hold IME events until compositionend if composition mode', fakeAsync(() => {
TestBed.overrideComponent(StandaloneNgModel, {
set: {providers: [{provide: COMPOSITION_BUFFER_MODE, useValue: true}]},
});
const fixture = initTest(StandaloneNgModel);
const inputEl = fixture.debugElement.query(By.css('input'));
const inputNativeEl = inputEl.nativeElement;
fixture.componentInstance.name = 'oldValue';
fixture.detectChanges();
tick();
expect(inputNativeEl.value).toEqual('oldValue');
inputEl.triggerEventHandler('compositionstart');
inputNativeEl.value = 'updatedValue';
dispatchEvent(inputNativeEl, 'input');
tick();
// ngModel should not update when compositionstart
expect(fixture.componentInstance.name).toEqual('oldValue');
inputEl.triggerEventHandler('compositionend', {target: {value: 'updatedValue'}});
fixture.detectChanges();
tick();
// ngModel should update when compositionend
expect(fixture.componentInstance.name).toEqual('updatedValue');
}));
it('should work normally with composition events if composition mode is off', fakeAsync(() => {
TestBed.overrideComponent(StandaloneNgModel, {
set: {providers: [{provide: COMPOSITION_BUFFER_MODE, useValue: false}]},
});
const fixture = initTest(StandaloneNgModel);
const inputEl = fixture.debugElement.query(By.css('input'));
const inputNativeEl = inputEl.nativeElement;
fixture.componentInstance.name = 'oldValue';
fixture.detectChanges();
tick();
expect(inputNativeEl.value).toEqual('oldValue');
inputEl.triggerEventHandler('compositionstart');
inputNativeEl.value = 'updatedValue';
dispatchEvent(inputNativeEl, 'input');
tick();
// ngModel should update normally
expect(fixture.componentInstance.name).toEqual('updatedValue');
}));
});
describe('ngModel corner cases', () => {
it('should update the view when the model is set back to what used to be in the view', fakeAsync(() => {
const fixture = initTest(StandaloneNgModel);
fixture.componentInstance.name = '';
fixture.detectChanges();
tick();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'aa';
input.selectionStart = 1;
dispatchEvent(input, 'input');
fixture.detectChanges();
tick();
expect(fixture.componentInstance.name).toEqual('aa');
// Programmatically update the input value to be "bb".
fixture.componentInstance.name = 'bb';
fixture.detectChanges();
tick();
expect(input.value).toEqual('bb');
// Programatically set it back to "aa".
fixture.componentInstance.name = 'aa';
fixture.detectChanges();
tick();
expect(input.value).toEqual('aa');
}));
it('should not crash when validity is checked from a binding', fakeAsync(() => {
const fixture = initTest(NgModelValidBinding);
tick();
expect(() => fixture.detectChanges()).not.toThrowError();
}));
});
});
@Component({
selector: 'standalone-ng-model',
template: `
<input type="text" [(ngModel)]="name">
`,
standalone: false,
})
class StandaloneNgModel {
name!: string;
}
@Component({
selector: 'ng-model-form',
template: `
<form (ngSubmit)="event=$event" (reset)="onReset()">
<input name="name" [(ngModel)]="name" minlength="10" [ngModelOptions]="options">
</form>
`,
standalone: false,
})
class NgModelForm {
name!: string | null;
event!: Event;
options = {};
onReset() {}
}
@Component({
selector: 'ng-model-native-validate-form',
template: `<form ngNativeValidate></form>`,
standalone: false,
})
class NgModelNativeValidateForm {}
@Component({
selector: 'ng-model-group-form',
template: `
<form>
<div ngModelGroup="name">
<input name="first" [(ngModel)]="first" required [disabled]="isDisabled">
<input name="last" [(ngModel)]="last">
</div>
<input name="email" [(ngModel)]="email" [ngModelOptions]="options">
</form>
`,
standalone: false,
})
class NgModelGroupForm {
first!: string;
last!: string;
email!: string;
isDisabled!: boolean;
options = {updateOn: 'change'};
}
@Component({
selector: 'ng-model-valid-binding',
template: `
<form>
<div ngModelGroup="name" #group="ngModelGroup">
<input name="first" [(ngModel)]="first" required>
{{ group.valid }}
</div>
</form>
`,
standalone: false,
})
class NgModelValidBinding {
first!: string;
}
@Component({
selector: 'ng-model-ngif-form',
template: `
<form>
<div ngModelGroup="name" *ngIf="groupShowing">
<input name="first" [(ngModel)]="first">
</div>
<input name="email" [(ngModel)]="email" *ngIf="emailShowing">
</form>
`,
standalone: false,
})
class NgModelNgIfForm {
first!: string;
groupShowing = true;
emailShowing = true;
email!: string;
}
@Component({
selector: 'ng-model-nested',
template: `
<form>
<div ngModelGroup="contact-info">
<input name="first" [(ngModel)]="first">
<div ngModelGroup="other-names">
<input name="other-names" [(ngModel)]="other">
</div>
</div>
</form>
`,
standalone: false,
})
class NgModelNestedForm {
first!: string;
other!: string;
}
@Component({
selector: 'ng-no-form',
template: `
<form ngNoForm>
<input name="name">
</form>
`,
standalone: false,
})
class NgNoFormComp {}
@Component({
selector: 'invalid-ng-model-noname',
template: `
<form>
<input [(ngModel)]="name">
</form>
`,
standalone: false,
})
class InvalidNgModelNoName {}
@Component({
selector: 'ng-model-options-standalone',
template: `
<form [ngFormOptions]="formOptions">
<input name="one" [(ngModel)]="one">
<input [(ngModel)]="two" [ngModelOptions]="options">
</form>
`,
standalone: false,
})
class NgModelOptionsStandalone {
one!: string;
two!: string;
options: {name?: string; standalone?: boolean; updateOn?: string} = {standalone: true};
formOptions = {};
}
@Component({
selector: 'ng-model-validation-bindings',
template: `
<form>
<input name="required" ngModel [required]="required">
<input name="minlength" ngModel [minlength]="minLen">
<input name="maxlength" ngModel [maxlength]="maxLen">
<input name="pattern" ngModel [pattern]="pattern">
</form>
`,
standalone: false,
})
class NgModelValidationBindings {
required!: boolean;
minLen!: number;
maxLen!: number;
pattern!: string;
}
@Component({
selector: 'ng-model-multiple-validators',
template: `
<form>
<input name="tovalidate" ngModel [required]="required" [minlength]="minLen" [pattern]="pattern">
</form>
`,
standalone: false,
})
class NgModelMultipleValidators {
required!: boolean;
minLen!: number;
pattern!: string | RegExp;
}
| {
"end_byte": 104640,
"start_byte": 96379,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/template_integration_spec.ts_104642_107684 | Component({
selector: 'ng-model-checkbox-validator',
template: `<form><input type="checkbox" [(ngModel)]="accepted" [required]="required" name="checkbox"></form>`,
standalone: false,
})
class NgModelCheckboxRequiredValidator {
accepted: boolean = false;
required: boolean = false;
}
@Component({
selector: 'ng-model-email',
template: `<form><input type="email" ngModel [email]="validatorEnabled" name="email"></form>`,
standalone: false,
})
class NgModelEmailValidator {
validatorEnabled: boolean = false;
}
@Directive({
selector: '[ng-async-validator]',
providers: [
{provide: NG_ASYNC_VALIDATORS, useExisting: forwardRef(() => NgAsyncValidator), multi: true},
],
standalone: false,
})
class NgAsyncValidator implements AsyncValidator {
validate(c: AbstractControl) {
return Promise.resolve(null);
}
}
@Component({
selector: 'ng-model-async-validation',
template: `<input name="async" ngModel ng-async-validator>`,
standalone: false,
})
class NgModelAsyncValidation {}
@Component({
selector: 'ng-model-changes-form',
template: `
<form>
<input name="async" [ngModel]="name" (ngModelChange)="log()"
[ngModelOptions]="options">
</form>
`,
standalone: false,
})
class NgModelChangesForm {
name!: string;
events: string[] = [];
options: any;
log() {
this.events.push('fired');
}
}
@Component({
selector: 'ng-model-change-state',
template: `
<input #ngModel="ngModel" ngModel [maxlength]="4"
(ngModelChange)="onNgModelChange(ngModel)">
`,
standalone: false,
})
class NgModelChangeState {
onNgModelChange = () => {};
}
@Component({
selector: 'ng-model-max',
template: `<form><input name="max" type="number" ngModel [max]="max"></form>`,
standalone: false,
})
class NgModelMaxValidator {
max!: number;
}
@Component({
selector: 'ng-model-min',
template: `<form><input name="min" type="number" ngModel [min]="min"></form>`,
standalone: false,
})
class NgModelMinValidator {
min!: number;
}
@Component({
selector: 'ng-model-min-max',
template: `
<form><input name="min_max" type="number" ngModel [min]="min" [max]="max"></form>`,
standalone: false,
})
class NgModelMinMaxValidator {
min!: number | string;
max!: number | string;
}
@Directive({
selector: '[myDir]',
standalone: false,
})
class CustomDirective {
@Input() min!: number;
@Input() max!: number;
}
@Component({
selector: 'ng-model-no-min-max',
template: `
<form>
<input name="min" type="text" ngModel [min]="min" myDir>
<input name="max" type="text" ngModel [max]="max" myDir>
</form>
`,
standalone: false,
})
class NgModelNoMinMaxValidator {
min!: number;
max!: number;
@ViewChild('myDir') myDir: any;
}
@Component({
selector: 'ng-model-nested',
template: `
<dialog open>
<form #form method="dialog">
<button>Submit</button>
</form>
</dialog>
`,
standalone: false,
})
class NativeDialogForm {
@ViewChild('form') form!: ElementRef<HTMLFormElement>;
}
| {
"end_byte": 107684,
"start_byte": 104642,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/template_integration_spec.ts"
} |
angular/packages/forms/test/form_builder_spec.ts_0_466 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
import {fakeAsync, TestBed, tick} from '@angular/core/testing';
import {
FormBuilder,
NonNullableFormBuilder,
ReactiveFormsModule,
UntypedFormBuilder,
Validators,
} from '@angular/forms';
import {of} from 'rxjs'; | {
"end_byte": 466,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_builder_spec.ts"
} |
angular/packages/forms/test/form_builder_spec.ts_468_8864 | (function () {
function syncValidator() {
return null;
}
function asyncValidator() {
return Promise.resolve(null);
}
describe('Form Builder', () => {
let b: FormBuilder;
beforeEach(() => {
b = new FormBuilder();
});
it('should create controls from a value', () => {
const g = b.group({'login': 'some value'});
expect(g.controls['login'].value).toEqual('some value');
});
it('should create controls from a boxed value', () => {
const g = b.group({'login': {value: 'some value', disabled: true}});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].disabled).toEqual(true);
});
it('should create controls from an array', () => {
const g = b.group({
'login': ['some value'],
'password': ['some value', syncValidator, asyncValidator],
});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['password'].value).toEqual('some value');
expect(g.controls['password'].validator).toEqual(syncValidator);
expect(g.controls['password'].asyncValidator).toEqual(asyncValidator);
});
it('should use controls whose form state is a primitive value', () => {
const g = b.group({'login': b.control('some value', syncValidator, asyncValidator)});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should create controls from FormStates', () => {
const c = b.control({value: 'one', disabled: false});
expect(c.value).toEqual('one');
c.reset();
expect(c.value).toEqual(null);
});
it('should work on a directly constructed FormBuilder object', () => {
const g = b.group({'login': 'some value'});
expect(g.controls['login'].value).toEqual('some value');
});
describe('should create control records', () => {
it('from simple values', () => {
const a = b.record({a: 'one', b: 'two'});
expect(a.value).toEqual({a: 'one', b: 'two'});
});
it('from boxed values', () => {
const a = b.record({a: 'one', b: {value: 'two', disabled: true}});
expect(a.value).toEqual({a: 'one'});
a.get('b')?.enable();
expect(a.value).toEqual({a: 'one', b: 'two'});
});
it('from an array', () => {
const a = b.record({a: ['one']});
expect(a.value).toEqual({a: 'one'});
});
it('from controls whose form state is a primitive value', () => {
const record = b.record({'login': b.control('some value', syncValidator, asyncValidator)});
expect(record.controls['login'].value).toEqual('some value');
expect(record.controls['login'].validator).toBe(syncValidator);
expect(record.controls['login'].asyncValidator).toBe(asyncValidator);
});
});
it('should create homogenous control arrays', () => {
const a = b.array(['one', 'two', 'three']);
expect(a.value).toEqual(['one', 'two', 'three']);
});
it('should create control arrays with FormStates and ControlConfigs', () => {
const a = b.array(['one', 'two', {value: 'three', disabled: false}]);
expect(a.value).toEqual(['one', 'two', 'three']);
});
it('should create control arrays with ControlConfigs', () => {
const a = b.array([['one', syncValidator, asyncValidator]]);
expect(a.value).toEqual(['one']);
expect(a.controls[0].validator).toBe(syncValidator);
expect(a.controls[0].asyncValidator).toBe(asyncValidator);
});
it('should create nested control arrays with ControlConfigs', () => {
const a = b.array(['one', ['two', syncValidator, asyncValidator]]);
expect(a.value).toEqual(['one', 'two']);
expect(a.controls[1].validator).toBe(syncValidator);
expect(a.controls[1].asyncValidator).toBe(asyncValidator);
});
it('should create control arrays with AbstractControls', () => {
const ctrl = b.control('one');
const a = b.array([ctrl], syncValidator, asyncValidator);
expect(a.value).toEqual(['one']);
expect(a.validator).toBe(syncValidator);
expect(a.asyncValidator).toBe(asyncValidator);
});
it('should create control arrays with mixed value representations', () => {
const a = b.array([
'one',
['two', syncValidator, asyncValidator],
{value: 'three', disabled: false},
[{value: 'four', disabled: false}, syncValidator, asyncValidator],
['five'],
b.control('six'),
b.control({value: 'seven', disabled: false}),
]);
expect(a.value).toEqual(['one', 'two', 'three', 'four', 'five', 'six', 'seven']);
});
it('should support controls with no validators and whose form state is null', () => {
const g = b.group({'login': b.control(null)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBeNull();
expect(g.controls['login'].asyncValidator).toBeNull();
});
it('should support controls with validators and whose form state is null', () => {
const g = b.group({'login': b.control(null, syncValidator, asyncValidator)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should support controls with validators that are later modified', () => {
const g = b.group({'login': b.control(null, syncValidator, asyncValidator)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
g.controls['login'].addValidators(Validators.required);
expect(g.controls['login'].hasValidator(Validators.required)).toBe(true);
g.controls['login'].removeValidators(Validators.required);
expect(g.controls['login'].hasValidator(Validators.required)).toBe(false);
});
it('should support controls with no validators and whose form state is undefined', () => {
const g = b.group({'login': b.control(undefined)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBeNull();
expect(g.controls['login'].asyncValidator).toBeNull();
});
it('should support controls with validators and whose form state is undefined', () => {
const g = b.group({'login': b.control(undefined, syncValidator, asyncValidator)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should create groups with a custom validator', () => {
const g = b.group(
{'login': 'some value'},
{'validator': syncValidator, 'asyncValidator': asyncValidator},
);
expect(g.validator).toBe(syncValidator);
expect(g.asyncValidator).toBe(asyncValidator);
});
it('should create groups with null options', () => {
const g = b.group({'login': 'some value'}, null);
expect(g.validator).toBe(null);
expect(g.asyncValidator).toBe(null);
});
it('should create groups with shorthand parameters and with right typings', () => {
const form = b.group({
shorthand: [3, Validators.required],
shorthand2: [5, {validators: Validators.required}],
});
expect(form.get('shorthand')?.value).toEqual(3);
expect((form.get('shorthand2')!.value ?? 0) + 0).toEqual(5);
const form2 = b.group({
shorthand2: [5, {updateOn: 'blur'}],
});
expect((form2.get('shorthand2')!.value ?? 0) + 0).toEqual(5);
});
it('should create control arrays', () => {
const c = b.control('three');
const e = b.control(null);
const f = b.control(undefined);
const a = b.array(
['one' as any, ['two', syncValidator], c, b.array(['four']), e, f],
syncValidator,
asyncValidator,
);
expect(a.value).toEqual(['one', 'two', 'three', ['four'], null, null]);
expect(a.validator).toBe(syncValidator);
expect(a.asyncValidator).toBe(asyncValidator);
}); | {
"end_byte": 8864,
"start_byte": 468,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_builder_spec.ts"
} |
angular/packages/forms/test/form_builder_spec.ts_8870_14811 | it('should create control arrays with multiple async validators', fakeAsync(() => {
function asyncValidator1() {
return of({'async1': true});
}
function asyncValidator2() {
return of({'async2': true});
}
const a = b.array(['one', 'two'], null, [asyncValidator1, asyncValidator2]);
expect(a.value).toEqual(['one', 'two']);
tick();
expect(a.errors).toEqual({'async1': true, 'async2': true});
}));
it('should create control arrays with multiple sync validators', () => {
function syncValidator1() {
return {'sync1': true};
}
function syncValidator2() {
return {'sync2': true};
}
const a = b.array(['one', 'two'], [syncValidator1, syncValidator2]);
expect(a.value).toEqual(['one', 'two']);
expect(a.errors).toEqual({'sync1': true, 'sync2': true});
});
it('should be injectable', () => {
@Component({
standalone: true,
template: '...',
})
class MyComp {
constructor(public fb: FormBuilder) {}
}
TestBed.configureTestingModule({imports: [ReactiveFormsModule]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.fb).toBeInstanceOf(FormBuilder);
const fc = fixture.componentInstance.fb.control('foo');
{
// Check the type of the value by assigning in each direction
type ValueType = string | null;
let t: ValueType = fc.value;
let t1 = fc.value;
t1 = null as unknown as ValueType;
}
fc.reset();
expect(fc.value).toEqual(null);
});
it('should be injectable as NonNullableFormBuilder', () => {
@Component({
standalone: true,
template: '...',
})
class MyComp {
constructor(public fb: NonNullableFormBuilder) {}
}
TestBed.configureTestingModule({imports: [ReactiveFormsModule]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.fb).toBeInstanceOf(FormBuilder);
const fc = fixture.componentInstance.fb.control('foo');
{
// Check the type of the value by assigning in each direction
type ValueType = string;
let t: ValueType = fc.value;
let t1 = fc.value;
t1 = null as unknown as ValueType;
}
fc.reset();
expect(fc.value).toEqual('foo');
});
describe('updateOn', () => {
it('should default to on change', () => {
const c = b.control('');
expect(c.updateOn).toEqual('change');
});
it('should default to on change with an options obj', () => {
const c = b.control('', {validators: Validators.required});
expect(c.updateOn).toEqual('change');
});
it('should set updateOn when updating on blur', () => {
const c = b.control('', {updateOn: 'blur'});
expect(c.updateOn).toEqual('blur');
});
describe('in groups and arrays', () => {
it('should default to group updateOn when not set in control', () => {
const g = b.group({one: b.control(''), two: b.control('')}, {updateOn: 'blur'});
expect(g.get('one')!.updateOn).toEqual('blur');
expect(g.get('two')!.updateOn).toEqual('blur');
});
it('should default to array updateOn when not set in control', () => {
const a = b.array([b.control(''), b.control('')], {updateOn: 'blur'});
expect(a.get([0])!.updateOn).toEqual('blur');
expect(a.get([1])!.updateOn).toEqual('blur');
});
it('should set updateOn with nested groups', () => {
const g = b.group(
{
group: b.group({one: b.control(''), two: b.control('')}),
},
{updateOn: 'blur'},
);
expect(g.get('group.one')!.updateOn).toEqual('blur');
expect(g.get('group.two')!.updateOn).toEqual('blur');
expect(g.get('group')!.updateOn).toEqual('blur');
});
it('should set updateOn with nested arrays', () => {
const g = b.group(
{
arr: b.array([b.control(''), b.control('')]),
},
{updateOn: 'blur'},
);
expect(g.get(['arr', 0])!.updateOn).toEqual('blur');
expect(g.get(['arr', 1])!.updateOn).toEqual('blur');
expect(g.get('arr')!.updateOn).toEqual('blur');
});
it('should allow control updateOn to override group updateOn', () => {
const g = b.group(
{one: b.control('', {updateOn: 'change'}), two: b.control('')},
{updateOn: 'blur'},
);
expect(g.get('one')!.updateOn).toEqual('change');
expect(g.get('two')!.updateOn).toEqual('blur');
});
it('should set updateOn with complex setup', () => {
const g = b.group({
group: b.group(
{one: b.control('', {updateOn: 'change'}), two: b.control('')},
{updateOn: 'blur'},
),
groupTwo: b.group({one: b.control('')}, {updateOn: 'submit'}),
three: b.control(''),
});
expect(g.get('group.one')!.updateOn).toEqual('change');
expect(g.get('group.two')!.updateOn).toEqual('blur');
expect(g.get('groupTwo.one')!.updateOn).toEqual('submit');
expect(g.get('three')!.updateOn).toEqual('change');
});
});
});
});
describe('UntypedFormBuilder', () => {
let fb: FormBuilder = new FormBuilder();
let ufb: UntypedFormBuilder = new UntypedFormBuilder();
function typedFn(fb: FormBuilder): void {}
function untypedFn(fb: UntypedFormBuilder): void {}
it('can be provided where a FormBuilder is expected and vice versa', () => {
typedFn(ufb);
untypedFn(fb);
});
});
})(); | {
"end_byte": 14811,
"start_byte": 8870,
"url": "https://github.com/angular/angular/blob/main/packages/forms/test/form_builder_spec.ts"
} |
angular/packages/forms/src/errors.ts_0_1180 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* The list of error codes used in runtime code of the `forms` package.
* Reserved error code range: 1000-1999.
*/
export const enum RuntimeErrorCode {
// Structure validation errors (10xx)
NO_CONTROLS = 1000,
MISSING_CONTROL = 1001,
MISSING_CONTROL_VALUE = 1002,
// Reactive Forms errors (1050-1099)
FORM_CONTROL_NAME_MISSING_PARENT = 1050,
FORM_CONTROL_NAME_INSIDE_MODEL_GROUP = 1051,
FORM_GROUP_MISSING_INSTANCE = 1052,
FORM_GROUP_NAME_MISSING_PARENT = 1053,
FORM_ARRAY_NAME_MISSING_PARENT = 1054,
// Validators errors (11xx)
WRONG_VALIDATOR_RETURN_TYPE = -1101,
// Value Accessor Errors (12xx)
NG_VALUE_ACCESSOR_NOT_PROVIDED = 1200,
COMPAREWITH_NOT_A_FN = 1201,
NAME_AND_FORM_CONTROL_NAME_MUST_MATCH = 1202,
NG_MISSING_VALUE_ACCESSOR = -1203,
// Template-driven Forms errors (1350-1399)
NGMODEL_IN_FORM_GROUP = 1350,
NGMODEL_IN_FORM_GROUP_NAME = 1351,
NGMODEL_WITHOUT_NAME = 1352,
NGMODELGROUP_IN_FORM_GROUP = 1353,
}
| {
"end_byte": 1180,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/errors.ts"
} |
angular/packages/forms/src/form_providers.ts_0_3134 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ModuleWithProviders, NgModule} from '@angular/core';
import {
InternalFormsSharedModule,
NG_MODEL_WITH_FORM_CONTROL_WARNING,
REACTIVE_DRIVEN_DIRECTIVES,
TEMPLATE_DRIVEN_DIRECTIVES,
} from './directives';
import {
CALL_SET_DISABLED_STATE,
setDisabledStateDefault,
SetDisabledStateOption,
} from './directives/shared';
/**
* Exports the required providers and directives for template-driven forms,
* making them available for import by NgModules that import this module.
*
* @see [Forms Overview](guide/forms)
* @see [Template-driven Forms Guide](guide/forms)
*
* @publicApi
*/
@NgModule({
declarations: TEMPLATE_DRIVEN_DIRECTIVES,
exports: [InternalFormsSharedModule, TEMPLATE_DRIVEN_DIRECTIVES],
})
export class FormsModule {
/**
* @description
* Provides options for configuring the forms module.
*
* @param opts An object of configuration options
* * `callSetDisabledState` Configures whether to `always` call `setDisabledState`, which is more
* correct, or to only call it `whenDisabled`, which is the legacy behavior.
*/
static withConfig(opts: {
callSetDisabledState?: SetDisabledStateOption;
}): ModuleWithProviders<FormsModule> {
return {
ngModule: FormsModule,
providers: [
{
provide: CALL_SET_DISABLED_STATE,
useValue: opts.callSetDisabledState ?? setDisabledStateDefault,
},
],
};
}
}
/**
* Exports the required infrastructure and directives for reactive forms,
* making them available for import by NgModules that import this module.
*
* @see [Forms Overview](guide/forms)
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
*
* @publicApi
*/
@NgModule({
declarations: [REACTIVE_DRIVEN_DIRECTIVES],
exports: [InternalFormsSharedModule, REACTIVE_DRIVEN_DIRECTIVES],
})
export class ReactiveFormsModule {
/**
* @description
* Provides options for configuring the reactive forms module.
*
* @param opts An object of configuration options
* * `warnOnNgModelWithFormControl` Configures when to emit a warning when an `ngModel`
* binding is used with reactive form directives.
* * `callSetDisabledState` Configures whether to `always` call `setDisabledState`, which is more
* correct, or to only call it `whenDisabled`, which is the legacy behavior.
*/
static withConfig(opts: {
/** @deprecated as of v6 */ warnOnNgModelWithFormControl?: 'never' | 'once' | 'always';
callSetDisabledState?: SetDisabledStateOption;
}): ModuleWithProviders<ReactiveFormsModule> {
return {
ngModule: ReactiveFormsModule,
providers: [
{
provide: NG_MODEL_WITH_FORM_CONTROL_WARNING,
useValue: opts.warnOnNgModelWithFormControl ?? 'always',
},
{
provide: CALL_SET_DISABLED_STATE,
useValue: opts.callSetDisabledState ?? setDisabledStateDefault,
},
],
};
}
}
| {
"end_byte": 3134,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/form_providers.ts"
} |
angular/packages/forms/src/directives.ts_0_4285 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule, Type} from '@angular/core';
import {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';
import {DefaultValueAccessor} from './directives/default_value_accessor';
import {NgControlStatus, NgControlStatusGroup} from './directives/ng_control_status';
import {NgForm} from './directives/ng_form';
import {NgModel} from './directives/ng_model';
import {NgModelGroup} from './directives/ng_model_group';
import {NgNoValidate} from './directives/ng_no_validate_directive';
import {NumberValueAccessor} from './directives/number_value_accessor';
import {RadioControlValueAccessor} from './directives/radio_control_value_accessor';
import {RangeValueAccessor} from './directives/range_value_accessor';
import {FormControlDirective} from './directives/reactive_directives/form_control_directive';
import {FormControlName} from './directives/reactive_directives/form_control_name';
import {FormGroupDirective} from './directives/reactive_directives/form_group_directive';
import {FormArrayName, FormGroupName} from './directives/reactive_directives/form_group_name';
import {
NgSelectOption,
SelectControlValueAccessor,
} from './directives/select_control_value_accessor';
import {
NgSelectMultipleOption,
SelectMultipleControlValueAccessor,
} from './directives/select_multiple_control_value_accessor';
import {
CheckboxRequiredValidator,
EmailValidator,
MaxLengthValidator,
MaxValidator,
MinLengthValidator,
MinValidator,
PatternValidator,
RequiredValidator,
} from './directives/validators';
export {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';
export {ControlValueAccessor} from './directives/control_value_accessor';
export {DefaultValueAccessor} from './directives/default_value_accessor';
export {NgControl} from './directives/ng_control';
export {NgControlStatus, NgControlStatusGroup} from './directives/ng_control_status';
export {NgForm} from './directives/ng_form';
export {NgModel} from './directives/ng_model';
export {NgModelGroup} from './directives/ng_model_group';
export {NumberValueAccessor} from './directives/number_value_accessor';
export {RadioControlValueAccessor} from './directives/radio_control_value_accessor';
export {RangeValueAccessor} from './directives/range_value_accessor';
export {
FormControlDirective,
NG_MODEL_WITH_FORM_CONTROL_WARNING,
} from './directives/reactive_directives/form_control_directive';
export {FormControlName} from './directives/reactive_directives/form_control_name';
export {FormGroupDirective} from './directives/reactive_directives/form_group_directive';
export {FormArrayName, FormGroupName} from './directives/reactive_directives/form_group_name';
export {
NgSelectOption,
SelectControlValueAccessor,
} from './directives/select_control_value_accessor';
export {
NgSelectMultipleOption,
SelectMultipleControlValueAccessor,
} from './directives/select_multiple_control_value_accessor';
export {CALL_SET_DISABLED_STATE} from './directives/shared';
export const SHARED_FORM_DIRECTIVES: Type<any>[] = [
NgNoValidate,
NgSelectOption,
NgSelectMultipleOption,
DefaultValueAccessor,
NumberValueAccessor,
RangeValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
NgControlStatus,
NgControlStatusGroup,
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator,
CheckboxRequiredValidator,
EmailValidator,
MinValidator,
MaxValidator,
];
export const TEMPLATE_DRIVEN_DIRECTIVES: Type<any>[] = [NgModel, NgModelGroup, NgForm];
export const REACTIVE_DRIVEN_DIRECTIVES: Type<any>[] = [
FormControlDirective,
FormGroupDirective,
FormControlName,
FormGroupName,
FormArrayName,
];
/**
* Internal module used for sharing directives between FormsModule and ReactiveFormsModule
*/
@NgModule({
declarations: SHARED_FORM_DIRECTIVES,
exports: SHARED_FORM_DIRECTIVES,
})
export class ɵInternalFormsSharedModule {}
export {ɵInternalFormsSharedModule as InternalFormsSharedModule};
| {
"end_byte": 4285,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives.ts"
} |
angular/packages/forms/src/forms.ts_0_3881 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* This module is used for handling user input, by defining and building a `FormGroup` that
* consists of `FormControl` objects, and mapping them onto the DOM. `FormControl`
* objects can then be used to read information from the form DOM elements.
*
* Forms providers are not included in default providers; you must import these providers
* explicitly.
*/
export {ɵInternalFormsSharedModule} from './directives';
export {AbstractControlDirective} from './directives/abstract_control_directive';
export {AbstractFormGroupDirective} from './directives/abstract_form_group_directive';
export {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';
export {ControlContainer} from './directives/control_container';
export {ControlValueAccessor, NG_VALUE_ACCESSOR} from './directives/control_value_accessor';
export {COMPOSITION_BUFFER_MODE, DefaultValueAccessor} from './directives/default_value_accessor';
export {Form} from './directives/form_interface';
export {NgControl} from './directives/ng_control';
export {NgControlStatus, NgControlStatusGroup} from './directives/ng_control_status';
export {NgForm} from './directives/ng_form';
export {NgModel} from './directives/ng_model';
export {NgModelGroup} from './directives/ng_model_group';
export {ɵNgNoValidate} from './directives/ng_no_validate_directive';
export {NumberValueAccessor} from './directives/number_value_accessor';
export {RadioControlValueAccessor} from './directives/radio_control_value_accessor';
export {RangeValueAccessor} from './directives/range_value_accessor';
export {FormControlDirective} from './directives/reactive_directives/form_control_directive';
export {FormControlName} from './directives/reactive_directives/form_control_name';
export {FormGroupDirective} from './directives/reactive_directives/form_group_directive';
export {FormArrayName, FormGroupName} from './directives/reactive_directives/form_group_name';
export {
NgSelectOption,
SelectControlValueAccessor,
} from './directives/select_control_value_accessor';
export {
SelectMultipleControlValueAccessor,
ɵNgSelectMultipleOption,
} from './directives/select_multiple_control_value_accessor';
export {SetDisabledStateOption} from './directives/shared';
export {
AsyncValidator,
AsyncValidatorFn,
CheckboxRequiredValidator,
EmailValidator,
MaxLengthValidator,
MaxValidator,
MinLengthValidator,
MinValidator,
PatternValidator,
RequiredValidator,
ValidationErrors,
Validator,
ValidatorFn,
} from './directives/validators';
export {
ControlConfig,
FormBuilder,
NonNullableFormBuilder,
UntypedFormBuilder,
ɵElement,
} from './form_builder';
export {
AbstractControl,
AbstractControlOptions,
ControlEvent,
FormControlStatus,
FormResetEvent,
FormSubmittedEvent,
PristineChangeEvent,
StatusChangeEvent,
TouchedChangeEvent,
ValueChangeEvent,
ɵCoerceStrArrToNumArr,
ɵGetProperty,
ɵNavigate,
ɵRawValue,
ɵTokenize,
ɵTypedOrUntyped,
ɵValue,
ɵWriteable,
} from './model/abstract_model';
export {
FormArray,
isFormArray,
UntypedFormArray,
ɵFormArrayRawValue,
ɵFormArrayValue,
} from './model/form_array';
export {
FormControl,
FormControlOptions,
FormControlState,
isFormControl,
UntypedFormControl,
ɵFormControlCtor,
} from './model/form_control';
export {
FormGroup,
FormRecord,
isFormGroup,
isFormRecord,
UntypedFormGroup,
ɵFormGroupRawValue,
ɵFormGroupValue,
ɵOptionalKeys,
} from './model/form_group';
export {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from './validators';
export {VERSION} from './version';
export * from './form_providers';
| {
"end_byte": 3881,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/forms.ts"
} |
angular/packages/forms/src/validators.ts_0_5317 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
InjectionToken,
ɵisPromise as isPromise,
ɵisSubscribable as isSubscribable,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {forkJoin, from, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import type {
AsyncValidator,
AsyncValidatorFn,
ValidationErrors,
Validator,
ValidatorFn,
} from './directives/validators';
import {RuntimeErrorCode} from './errors';
import type {AbstractControl} from './model/abstract_model';
function isEmptyInputValue(value: any): boolean {
/**
* Check if the object is a string or array before evaluating the length attribute.
* This avoids falsely rejecting objects that contain a custom length attribute.
* For example, the object {id: 1, length: 0, width: 0} should not be returned as empty.
*/
return (
value == null || ((typeof value === 'string' || Array.isArray(value)) && value.length === 0)
);
}
function hasValidLength(value: any): boolean {
// non-strict comparison is intentional, to check for both `null` and `undefined` values
return value != null && typeof value.length === 'number';
}
/**
* @description
* An `InjectionToken` for registering additional synchronous validators used with
* `AbstractControl`s.
*
* @see {@link NG_ASYNC_VALIDATORS}
*
* @usageNotes
*
* ### Providing a custom validator
*
* The following example registers a custom validator directive. Adding the validator to the
* existing collection of validators requires the `multi: true` option.
*
* ```typescript
* @Directive({
* selector: '[customValidator]',
* providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
* })
* class CustomValidatorDirective implements Validator {
* validate(control: AbstractControl): ValidationErrors | null {
* return { 'custom': true };
* }
* }
* ```
*
* @publicApi
*/
export const NG_VALIDATORS = new InjectionToken<ReadonlyArray<Validator | Function>>(
ngDevMode ? 'NgValidators' : '',
);
/**
* @description
* An `InjectionToken` for registering additional asynchronous validators used with
* `AbstractControl`s.
*
* @see {@link NG_VALIDATORS}
*
* @usageNotes
*
* ### Provide a custom async validator directive
*
* The following example implements the `AsyncValidator` interface to create an
* async validator directive with a custom error key.
*
* ```typescript
* @Directive({
* selector: '[customAsyncValidator]',
* providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi:
* true}]
* })
* class CustomAsyncValidatorDirective implements AsyncValidator {
* validate(control: AbstractControl): Promise<ValidationErrors|null> {
* return Promise.resolve({'custom': true});
* }
* }
* ```
*
* @publicApi
*/
export const NG_ASYNC_VALIDATORS = new InjectionToken<ReadonlyArray<Validator | Function>>(
ngDevMode ? 'NgAsyncValidators' : '',
);
/**
* A regular expression that matches valid e-mail addresses.
*
* At a high level, this regexp matches e-mail addresses of the format `local-part@tld`, where:
* - `local-part` consists of one or more of the allowed characters (alphanumeric and some
* punctuation symbols).
* - `local-part` cannot begin or end with a period (`.`).
* - `local-part` cannot be longer than 64 characters.
* - `tld` consists of one or more `labels` separated by periods (`.`). For example `localhost` or
* `foo.com`.
* - A `label` consists of one or more of the allowed characters (alphanumeric, dashes (`-`) and
* periods (`.`)).
* - A `label` cannot begin or end with a dash (`-`) or a period (`.`).
* - A `label` cannot be longer than 63 characters.
* - The whole address cannot be longer than 254 characters.
*
* ## Implementation background
*
* This regexp was ported over from AngularJS (see there for git history):
* https://github.com/angular/angular.js/blob/c133ef836/src/ng/directive/input.js#L27
* It is based on the
* [WHATWG version](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) with
* some enhancements to incorporate more RFC rules (such as rules related to domain names and the
* lengths of different parts of the address). The main differences from the WHATWG version are:
* - Disallow `local-part` to begin or end with a period (`.`).
* - Disallow `local-part` length to exceed 64 characters.
* - Disallow total address length to exceed 254 characters.
*
* See [this commit](https://github.com/angular/angular.js/commit/f3f5cf72e) for more details.
*/
const EMAIL_REGEXP =
/^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/**
* @description
* Provides a set of built-in validators that can be used by form controls.
*
* A validator is a function that processes a `FormControl` or collection of
* controls and returns an error map or null. A null map means that validation has passed.
*
* @see [Form Validation](guide/forms/form-validation)
*
* @publicApi
*/
ex | {
"end_byte": 5317,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/validators.ts"
} |
angular/packages/forms/src/validators.ts_5318_11893 | ort class Validators {
/**
* @description
* Validator that requires the control's value to be greater than or equal to the provided number.
*
* @usageNotes
*
* ### Validate against a minimum of 3
*
* ```typescript
* const control = new FormControl(2, Validators.min(3));
*
* console.log(control.errors); // {min: {min: 3, actual: 2}}
* ```
*
* @returns A validator function that returns an error map with the
* `min` property if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static min(min: number): ValidatorFn {
return minValidator(min);
}
/**
* @description
* Validator that requires the control's value to be less than or equal to the provided number.
*
* @usageNotes
*
* ### Validate against a maximum of 15
*
* ```typescript
* const control = new FormControl(16, Validators.max(15));
*
* console.log(control.errors); // {max: {max: 15, actual: 16}}
* ```
*
* @returns A validator function that returns an error map with the
* `max` property if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static max(max: number): ValidatorFn {
return maxValidator(max);
}
/**
* @description
* Validator that requires the control have a non-empty value.
*
* @usageNotes
*
* ### Validate that the field is non-empty
*
* ```typescript
* const control = new FormControl('', Validators.required);
*
* console.log(control.errors); // {required: true}
* ```
*
* @returns An error map with the `required` property
* if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static required(control: AbstractControl): ValidationErrors | null {
return requiredValidator(control);
}
/**
* @description
* Validator that requires the control's value be true. This validator is commonly
* used for required checkboxes.
*
* @usageNotes
*
* ### Validate that the field value is true
*
* ```typescript
* const control = new FormControl('some value', Validators.requiredTrue);
*
* console.log(control.errors); // {required: true}
* ```
*
* @returns An error map that contains the `required` property
* set to `true` if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static requiredTrue(control: AbstractControl): ValidationErrors | null {
return requiredTrueValidator(control);
}
/**
* @description
* Validator that requires the control's value pass an email validation test.
*
* Tests the value using a [regular
* expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
* pattern suitable for common use cases. The pattern is based on the definition of a valid email
* address in the [WHATWG HTML
* specification](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) with
* some enhancements to incorporate more RFC rules (such as rules related to domain names and the
* lengths of different parts of the address).
*
* The differences from the WHATWG version include:
* - Disallow `local-part` (the part before the `@` symbol) to begin or end with a period (`.`).
* - Disallow `local-part` to be longer than 64 characters.
* - Disallow the whole address to be longer than 254 characters.
*
* If this pattern does not satisfy your business needs, you can use `Validators.pattern()` to
* validate the value against a different pattern.
*
* @usageNotes
*
* ### Validate that the field matches a valid email pattern
*
* ```typescript
* const control = new FormControl('bad@', Validators.email);
*
* console.log(control.errors); // {email: true}
* ```
*
* @returns An error map with the `email` property
* if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static email(control: AbstractControl): ValidationErrors | null {
return emailValidator(control);
}
/**
* @description
* Validator that requires the length of the control's value to be greater than or equal
* to the provided minimum length. This validator is also provided by default if you use the
* the HTML5 `minlength` attribute. Note that the `minLength` validator is intended to be used
* only for types that have a numeric `length` property, such as strings or arrays. The
* `minLength` validator logic is also not invoked for values when their `length` property is 0
* (for example in case of an empty string or an empty array), to support optional controls. You
* can use the standard `required` validator if empty values should not be considered valid.
*
* @usageNotes
*
* ### Validate that the field has a minimum of 3 characters
*
* ```typescript
* const control = new FormControl('ng', Validators.minLength(3));
*
* console.log(control.errors); // {minlength: {requiredLength: 3, actualLength: 2}}
* ```
*
* ```html
* <input minlength="5">
* ```
*
* @returns A validator function that returns an error map with the
* `minlength` property if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static minLength(minLength: number): ValidatorFn {
return minLengthValidator(minLength);
}
/**
* @description
* Validator that requires the length of the control's value to be less than or equal
* to the provided maximum length. This validator is also provided by default if you use the
* the HTML5 `maxlength` attribute. Note that the `maxLength` validator is intended to be used
* only for types that have a numeric `length` property, such as strings or arrays.
*
* @usageNotes
*
* ### Validate that the field has maximum of 5 characters
*
* ```typescript
* const control = new FormControl('Angular', Validators.maxLength(5));
*
* console.log(control.errors); // {maxlength: {requiredLength: 5, actualLength: 7}}
* ```
*
* ```html
* <input maxlength="5">
* ```
*
* @returns A validator function that returns an error map with the
* `maxlength` property if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static maxLength(maxLength: number): ValidatorFn {
return maxLengthValidator(maxLength);
}
| {
"end_byte": 11893,
"start_byte": 5318,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/validators.ts"
} |
angular/packages/forms/src/validators.ts_11897_20402 |
* @description
* Validator that requires the control's value to match a regex pattern. This validator is also
* provided by default if you use the HTML5 `pattern` attribute.
*
* @usageNotes
*
* ### Validate that the field only contains letters or spaces
*
* ```typescript
* const control = new FormControl('1', Validators.pattern('[a-zA-Z ]*'));
*
* console.log(control.errors); // {pattern: {requiredPattern: '^[a-zA-Z ]*$', actualValue: '1'}}
* ```
*
* ```html
* <input pattern="[a-zA-Z ]*">
* ```
*
* ### Pattern matching with the global or sticky flag
*
* `RegExp` objects created with the `g` or `y` flags that are passed into `Validators.pattern`
* can produce different results on the same input when validations are run consecutively. This is
* due to how the behavior of `RegExp.prototype.test` is
* specified in [ECMA-262](https://tc39.es/ecma262/#sec-regexpbuiltinexec)
* (`RegExp` preserves the index of the last match when the global or sticky flag is used).
* Due to this behavior, it is recommended that when using
* `Validators.pattern` you **do not** pass in a `RegExp` object with either the global or sticky
* flag enabled.
*
* ```typescript
* // Not recommended (since the `g` flag is used)
* const controlOne = new FormControl('1', Validators.pattern(/foo/g));
*
* // Good
* const controlTwo = new FormControl('1', Validators.pattern(/foo/));
* ```
*
* @param pattern A regular expression to be used as is to test the values, or a string.
* If a string is passed, the `^` character is prepended and the `$` character is
* appended to the provided string (if not already present), and the resulting regular
* expression is used to test the values.
*
* @returns A validator function that returns an error map with the
* `pattern` property if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static pattern(pattern: string | RegExp): ValidatorFn {
return patternValidator(pattern);
}
/**
* @description
* Validator that performs no operation.
*
* @see {@link updateValueAndValidity()}
*
*/
static nullValidator(control: AbstractControl): ValidationErrors | null {
return nullValidator(control);
}
/**
* @description
* Compose multiple validators into a single function that returns the union
* of the individual error maps for the provided control.
*
* @returns A validator function that returns an error map with the
* merged error maps of the validators if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static compose(validators: null): null;
static compose(validators: (ValidatorFn | null | undefined)[]): ValidatorFn | null;
static compose(validators: (ValidatorFn | null | undefined)[] | null): ValidatorFn | null {
return compose(validators);
}
/**
* @description
* Compose multiple async validators into a single function that returns the union
* of the individual error objects for the provided control.
*
* @returns A validator function that returns an error map with the
* merged error objects of the async validators if the validation check fails, otherwise `null`.
*
* @see {@link updateValueAndValidity()}
*
*/
static composeAsync(validators: (AsyncValidatorFn | null)[]): AsyncValidatorFn | null {
return composeAsync(validators);
}
}
/**
* Validator that requires the control's value to be greater than or equal to the provided number.
* See `Validators.min` for additional information.
*/
export function minValidator(min: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isEmptyInputValue(control.value) || isEmptyInputValue(min)) {
return null; // don't validate empty values to allow optional controls
}
const value = parseFloat(control.value);
// Controls with NaN values after parsing should be treated as not having a
// minimum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-min
return !isNaN(value) && value < min ? {'min': {'min': min, 'actual': control.value}} : null;
};
}
/**
* Validator that requires the control's value to be less than or equal to the provided number.
* See `Validators.max` for additional information.
*/
export function maxValidator(max: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isEmptyInputValue(control.value) || isEmptyInputValue(max)) {
return null; // don't validate empty values to allow optional controls
}
const value = parseFloat(control.value);
// Controls with NaN values after parsing should be treated as not having a
// maximum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-max
return !isNaN(value) && value > max ? {'max': {'max': max, 'actual': control.value}} : null;
};
}
/**
* Validator that requires the control have a non-empty value.
* See `Validators.required` for additional information.
*/
export function requiredValidator(control: AbstractControl): ValidationErrors | null {
return isEmptyInputValue(control.value) ? {'required': true} : null;
}
/**
* Validator that requires the control's value be true. This validator is commonly
* used for required checkboxes.
* See `Validators.requiredTrue` for additional information.
*/
export function requiredTrueValidator(control: AbstractControl): ValidationErrors | null {
return control.value === true ? null : {'required': true};
}
/**
* Validator that requires the control's value pass an email validation test.
* See `Validators.email` for additional information.
*/
export function emailValidator(control: AbstractControl): ValidationErrors | null {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
return EMAIL_REGEXP.test(control.value) ? null : {'email': true};
}
/**
* Validator that requires the length of the control's value to be greater than or equal
* to the provided minimum length. See `Validators.minLength` for additional information.
*/
export function minLengthValidator(minLength: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isEmptyInputValue(control.value) || !hasValidLength(control.value)) {
// don't validate empty values to allow optional controls
// don't validate values without `length` property
return null;
}
return control.value.length < minLength
? {'minlength': {'requiredLength': minLength, 'actualLength': control.value.length}}
: null;
};
}
/**
* Validator that requires the length of the control's value to be less than or equal
* to the provided maximum length. See `Validators.maxLength` for additional information.
*/
export function maxLengthValidator(maxLength: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
return hasValidLength(control.value) && control.value.length > maxLength
? {'maxlength': {'requiredLength': maxLength, 'actualLength': control.value.length}}
: null;
};
}
/**
* Validator that requires the control's value to match a regex pattern.
* See `Validators.pattern` for additional information.
*/
export function patternValidator(pattern: string | RegExp): ValidatorFn {
if (!pattern) return nullValidator;
let regex: RegExp;
let regexStr: string;
if (typeof pattern === 'string') {
regexStr = '';
if (pattern.charAt(0) !== '^') regexStr += '^';
regexStr += pattern;
if (pattern.charAt(pattern.length - 1) !== '$') regexStr += '$';
regex = new RegExp(regexStr);
} else {
regexStr = pattern.toString();
regex = pattern;
}
return (control: AbstractControl): ValidationErrors | null => {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
const value: string = control.value;
return regex.test(value)
? null
: {'pattern': {'requiredPattern': regexStr, 'actualValue': value}};
};
}
/**
* Function that has `ValidatorFn` shape, but performs no operation.
*/
export function nullValidator(control: AbstractControl): ValidationErrors | null {
return null;
}
function isPresent(o: any): boolean {
return o != null;
}
e | {
"end_byte": 20402,
"start_byte": 11897,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/validators.ts"
} |
angular/packages/forms/src/validators.ts_20404_27538 | ort function toObservable(value: any): Observable<any> {
const obs = isPromise(value) ? from(value) : value;
if ((typeof ngDevMode === 'undefined' || ngDevMode) && !isSubscribable(obs)) {
let errorMessage = `Expected async validator to return Promise or Observable.`;
// A synchronous validator will return object or null.
if (typeof value === 'object') {
errorMessage +=
' Are you using a synchronous validator where an async validator is expected?';
}
throw new RuntimeError(RuntimeErrorCode.WRONG_VALIDATOR_RETURN_TYPE, errorMessage);
}
return obs;
}
function mergeErrors(arrayOfErrors: (ValidationErrors | null)[]): ValidationErrors | null {
let res: {[key: string]: any} = {};
arrayOfErrors.forEach((errors: ValidationErrors | null) => {
res = errors != null ? {...res!, ...errors} : res!;
});
return Object.keys(res).length === 0 ? null : res;
}
type GenericValidatorFn = (control: AbstractControl) => any;
function executeValidators<V extends GenericValidatorFn>(
control: AbstractControl,
validators: V[],
): ReturnType<V>[] {
return validators.map((validator) => validator(control));
}
function isValidatorFn<V>(validator: V | Validator | AsyncValidator): validator is V {
return !(validator as Validator).validate;
}
/**
* Given the list of validators that may contain both functions as well as classes, return the list
* of validator functions (convert validator classes into validator functions). This is needed to
* have consistent structure in validators list before composing them.
*
* @param validators The set of validators that may contain validators both in plain function form
* as well as represented as a validator class.
*/
export function normalizeValidators<V>(validators: (V | Validator | AsyncValidator)[]): V[] {
return validators.map((validator) => {
return isValidatorFn<V>(validator)
? validator
: (((c: AbstractControl) => validator.validate(c)) as unknown as V);
});
}
/**
* Merges synchronous validators into a single validator function.
* See `Validators.compose` for additional information.
*/
function compose(validators: (ValidatorFn | null | undefined)[] | null): ValidatorFn | null {
if (!validators) return null;
const presentValidators: ValidatorFn[] = validators.filter(isPresent) as any;
if (presentValidators.length == 0) return null;
return function (control: AbstractControl) {
return mergeErrors(executeValidators<ValidatorFn>(control, presentValidators));
};
}
/**
* Accepts a list of validators of different possible shapes (`Validator` and `ValidatorFn`),
* normalizes the list (converts everything to `ValidatorFn`) and merges them into a single
* validator function.
*/
export function composeValidators(validators: Array<Validator | ValidatorFn>): ValidatorFn | null {
return validators != null ? compose(normalizeValidators<ValidatorFn>(validators)) : null;
}
/**
* Merges asynchronous validators into a single validator function.
* See `Validators.composeAsync` for additional information.
*/
function composeAsync(validators: (AsyncValidatorFn | null)[]): AsyncValidatorFn | null {
if (!validators) return null;
const presentValidators: AsyncValidatorFn[] = validators.filter(isPresent) as any;
if (presentValidators.length == 0) return null;
return function (control: AbstractControl) {
const observables = executeValidators<AsyncValidatorFn>(control, presentValidators).map(
toObservable,
);
return forkJoin(observables).pipe(map(mergeErrors));
};
}
/**
* Accepts a list of async validators of different possible shapes (`AsyncValidator` and
* `AsyncValidatorFn`), normalizes the list (converts everything to `AsyncValidatorFn`) and merges
* them into a single validator function.
*/
export function composeAsyncValidators(
validators: Array<AsyncValidator | AsyncValidatorFn>,
): AsyncValidatorFn | null {
return validators != null
? composeAsync(normalizeValidators<AsyncValidatorFn>(validators))
: null;
}
/**
* Merges raw control validators with a given directive validator and returns the combined list of
* validators as an array.
*/
export function mergeValidators<V>(controlValidators: V | V[] | null, dirValidator: V): V[] {
if (controlValidators === null) return [dirValidator];
return Array.isArray(controlValidators)
? [...controlValidators, dirValidator]
: [controlValidators, dirValidator];
}
/**
* Retrieves the list of raw synchronous validators attached to a given control.
*/
export function getControlValidators(control: AbstractControl): ValidatorFn | ValidatorFn[] | null {
return (control as any)._rawValidators as ValidatorFn | ValidatorFn[] | null;
}
/**
* Retrieves the list of raw asynchronous validators attached to a given control.
*/
export function getControlAsyncValidators(
control: AbstractControl,
): AsyncValidatorFn | AsyncValidatorFn[] | null {
return (control as any)._rawAsyncValidators as AsyncValidatorFn | AsyncValidatorFn[] | null;
}
/**
* Accepts a singleton validator, an array, or null, and returns an array type with the provided
* validators.
*
* @param validators A validator, validators, or null.
* @returns A validators array.
*/
export function makeValidatorsArray<T extends ValidatorFn | AsyncValidatorFn>(
validators: T | T[] | null,
): T[] {
if (!validators) return [];
return Array.isArray(validators) ? validators : [validators];
}
/**
* Determines whether a validator or validators array has a given validator.
*
* @param validators The validator or validators to compare against.
* @param validator The validator to check.
* @returns Whether the validator is present.
*/
export function hasValidator<T extends ValidatorFn | AsyncValidatorFn>(
validators: T | T[] | null,
validator: T,
): boolean {
return Array.isArray(validators) ? validators.includes(validator) : validators === validator;
}
/**
* Combines two arrays of validators into one. If duplicates are provided, only one will be added.
*
* @param validators The new validators.
* @param currentValidators The base array of current validators.
* @returns An array of validators.
*/
export function addValidators<T extends ValidatorFn | AsyncValidatorFn>(
validators: T | T[],
currentValidators: T | T[] | null,
): T[] {
const current = makeValidatorsArray(currentValidators);
const validatorsToAdd = makeValidatorsArray(validators);
validatorsToAdd.forEach((v: T) => {
// Note: if there are duplicate entries in the new validators array,
// only the first one would be added to the current list of validators.
// Duplicate ones would be ignored since `hasValidator` would detect
// the presence of a validator function and we update the current list in place.
if (!hasValidator(current, v)) {
current.push(v);
}
});
return current;
}
export function removeValidators<T extends ValidatorFn | AsyncValidatorFn>(
validators: T | T[],
currentValidators: T | T[] | null,
): T[] {
return makeValidatorsArray(currentValidators).filter((v) => !hasValidator(validators, v));
}
| {
"end_byte": 27538,
"start_byte": 20404,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/validators.ts"
} |
angular/packages/forms/src/util.ts_0_341 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export function removeListItem<T>(list: T[], el: T): void {
const index = list.indexOf(el);
if (index > -1) list.splice(index, 1);
}
| {
"end_byte": 341,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/util.ts"
} |
angular/packages/forms/src/form_builder.ts_0_5188 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {inject, Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {AbstractControl, AbstractControlOptions, FormHooks} from './model/abstract_model';
import {FormArray, UntypedFormArray} from './model/form_array';
import {
FormControl,
FormControlOptions,
FormControlState,
UntypedFormControl,
} from './model/form_control';
import {FormGroup, FormRecord, UntypedFormGroup} from './model/form_group';
function isAbstractControlOptions(
options: AbstractControlOptions | {[key: string]: any} | null | undefined,
): options is AbstractControlOptions {
return (
!!options &&
((options as AbstractControlOptions).asyncValidators !== undefined ||
(options as AbstractControlOptions).validators !== undefined ||
(options as AbstractControlOptions).updateOn !== undefined)
);
}
/**
* The union of all validator types that can be accepted by a ControlConfig.
*/
type ValidatorConfig = ValidatorFn | AsyncValidatorFn | ValidatorFn[] | AsyncValidatorFn[];
/**
* The compiler may not always be able to prove that the elements of the control config are a tuple
* (i.e. occur in a fixed order). This slightly looser type is used for inference, to catch cases
* where the compiler cannot prove order and position.
*
* For example, consider the simple case `fb.group({foo: ['bar', Validators.required]})`. The
* compiler will infer this as an array, not as a tuple.
*/
type PermissiveControlConfig<T> = Array<T | FormControlState<T> | ValidatorConfig>;
/**
* Helper type to allow the compiler to accept [XXXX, { updateOn: string }] as a valid shorthand
* argument for .group()
*/
interface PermissiveAbstractControlOptions extends Omit<AbstractControlOptions, 'updateOn'> {
updateOn?: string;
}
/**
* ControlConfig<T> is a tuple containing a value of type T, plus optional validators and async
* validators.
*
* @publicApi
*/
export type ControlConfig<T> = [
T | FormControlState<T>,
(ValidatorFn | ValidatorFn[])?,
(AsyncValidatorFn | AsyncValidatorFn[])?,
];
/**
* FormBuilder accepts values in various container shapes, as well as raw values.
* Element returns the appropriate corresponding model class, given the container T.
* The flag N, if not never, makes the resulting `FormControl` have N in its type.
*/
export type ɵElement<T, N extends null> =
// The `extends` checks are wrapped in arrays in order to prevent TypeScript from applying type unions
// through the distributive conditional type. This is the officially recommended solution:
// https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
//
// Identify FormControl container types.
[T] extends [FormControl<infer U>]
? FormControl<U>
: // Or FormControl containers that are optional in their parent group.
[T] extends [FormControl<infer U> | undefined]
? FormControl<U>
: // FormGroup containers.
[T] extends [FormGroup<infer U>]
? FormGroup<U>
: // Optional FormGroup containers.
[T] extends [FormGroup<infer U> | undefined]
? FormGroup<U>
: // FormRecord containers.
[T] extends [FormRecord<infer U>]
? FormRecord<U>
: // Optional FormRecord containers.
[T] extends [FormRecord<infer U> | undefined]
? FormRecord<U>
: // FormArray containers.
[T] extends [FormArray<infer U>]
? FormArray<U>
: // Optional FormArray containers.
[T] extends [FormArray<infer U> | undefined]
? FormArray<U>
: // Otherwise unknown AbstractControl containers.
[T] extends [AbstractControl<infer U>]
? AbstractControl<U>
: // Optional AbstractControl containers.
[T] extends [AbstractControl<infer U> | undefined]
? AbstractControl<U>
: // FormControlState object container, which produces a nullable control.
[T] extends [FormControlState<infer U>]
? FormControl<U | N>
: // A ControlConfig tuple, which produces a nullable control.
[T] extends [PermissiveControlConfig<infer U>]
? FormControl<
Exclude<U, ValidatorConfig | PermissiveAbstractControlOptions> | N
>
: FormControl<T | N>;
/**
* @description
* Creates an `AbstractControl` from a user-specified configuration.
*
* The `FormBuilder` provides syntactic sugar that shortens creating instances of a
* `FormControl`, `FormGroup`, or `FormArray`. It reduces the amount of boilerplate needed to
* build complex forms.
*
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
*
* @publicApi
*/
| {
"end_byte": 5188,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/form_builder.ts"
} |
angular/packages/forms/src/form_builder.ts_5189_13095 | Injectable({providedIn: 'root'})
export class FormBuilder {
private useNonNullable: boolean = false;
/**
* @description
* Returns a FormBuilder in which automatically constructed `FormControl` elements
* have `{nonNullable: true}` and are non-nullable.
*
* **Constructing non-nullable controls**
*
* When constructing a control, it will be non-nullable, and will reset to its initial value.
*
* ```ts
* let nnfb = new FormBuilder().nonNullable;
* let name = nnfb.control('Alex'); // FormControl<string>
* name.reset();
* console.log(name); // 'Alex'
* ```
*
* **Constructing non-nullable groups or arrays**
*
* When constructing a group or array, all automatically created inner controls will be
* non-nullable, and will reset to their initial values.
*
* ```ts
* let nnfb = new FormBuilder().nonNullable;
* let name = nnfb.group({who: 'Alex'}); // FormGroup<{who: FormControl<string>}>
* name.reset();
* console.log(name); // {who: 'Alex'}
* ```
* **Constructing *nullable* fields on groups or arrays**
*
* It is still possible to have a nullable field. In particular, any `FormControl` which is
* *already* constructed will not be altered. For example:
*
* ```ts
* let nnfb = new FormBuilder().nonNullable;
* // FormGroup<{who: FormControl<string|null>}>
* let name = nnfb.group({who: new FormControl('Alex')});
* name.reset(); console.log(name); // {who: null}
* ```
*
* Because the inner control is constructed explicitly by the caller, the builder has
* no control over how it is created, and cannot exclude the `null`.
*/
get nonNullable(): NonNullableFormBuilder {
const nnfb = new FormBuilder();
nnfb.useNonNullable = true;
return nnfb as NonNullableFormBuilder;
}
/**
* @description
* Constructs a new `FormGroup` instance. Accepts a single generic argument, which is an object
* containing all the keys and corresponding inner control types.
*
* @param controls A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param options Configuration options object for the `FormGroup`. The object should have the
* `AbstractControlOptions` type and might contain the following fields:
* * `validators`: A synchronous validator function, or an array of validator functions.
* * `asyncValidators`: A single async validator or array of async validator functions.
* * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur'
* | submit').
*/
group<T extends {}>(
controls: T,
options?: AbstractControlOptions | null,
): FormGroup<{[K in keyof T]: ɵElement<T[K], null>}>;
/**
* @description
* Constructs a new `FormGroup` instance.
*
* @deprecated This API is not typesafe and can result in issues with Closure Compiler renaming.
* Use the `FormBuilder#group` overload with `AbstractControlOptions` instead.
* Note that `AbstractControlOptions` expects `validators` and `asyncValidators` to be valid
* validators. If you have custom validators, make sure their validation function parameter is
* `AbstractControl` and not a sub-class, such as `FormGroup`. These functions will be called
* with an object of type `AbstractControl` and that cannot be automatically downcast to a
* subclass, so TypeScript sees this as an error. For example, change the `(group: FormGroup) =>
* ValidationErrors|null` signature to be `(group: AbstractControl) => ValidationErrors|null`.
*
* @param controls A record of child controls. The key for each child is the name
* under which the control is registered.
*
* @param options Configuration options object for the `FormGroup`. The legacy configuration
* object consists of:
* * `validator`: A synchronous validator function, or an array of validator functions.
* * `asyncValidator`: A single async validator or array of async validator functions
* Note: the legacy format is deprecated and might be removed in one of the next major versions
* of Angular.
*/
group(controls: {[key: string]: any}, options: {[key: string]: any}): FormGroup;
group(
controls: {[key: string]: any},
options: AbstractControlOptions | {[key: string]: any} | null = null,
): FormGroup {
const reducedControls = this._reduceControls(controls);
let newOptions: FormControlOptions = {};
if (isAbstractControlOptions(options)) {
// `options` are `AbstractControlOptions`
newOptions = options;
} else if (options !== null) {
// `options` are legacy form group options
newOptions.validators = (options as any).validator;
newOptions.asyncValidators = (options as any).asyncValidator;
}
return new FormGroup(reducedControls, newOptions);
}
/**
* @description
* Constructs a new `FormRecord` instance. Accepts a single generic argument, which is an object
* containing all the keys and corresponding inner control types.
*
* @param controls A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param options Configuration options object for the `FormRecord`. The object should have the
* `AbstractControlOptions` type and might contain the following fields:
* * `validators`: A synchronous validator function, or an array of validator functions.
* * `asyncValidators`: A single async validator or array of async validator functions.
* * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur'
* | submit').
*/
record<T>(
controls: {[key: string]: T},
options: AbstractControlOptions | null = null,
): FormRecord<ɵElement<T, null>> {
const reducedControls = this._reduceControls(controls);
// Cast to `any` because the inferred types are not as specific as Element.
return new FormRecord(reducedControls, options) as any;
}
/** @deprecated Use `nonNullable` instead. */
control<T>(
formState: T | FormControlState<T>,
opts: FormControlOptions & {
initialValueIsDefault: true;
},
): FormControl<T>;
control<T>(
formState: T | FormControlState<T>,
opts: FormControlOptions & {nonNullable: true},
): FormControl<T>;
/**
* @deprecated When passing an `options` argument, the `asyncValidator` argument has no effect.
*/
control<T>(
formState: T | FormControlState<T>,
opts: FormControlOptions,
asyncValidator: AsyncValidatorFn | AsyncValidatorFn[],
): FormControl<T | null>;
control<T>(
formState: T | FormControlState<T>,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): FormControl<T | null>;
/**
* @description
* Constructs a new `FormControl` with the given state, validators and options. Sets
* `{nonNullable: true}` in the options to get a non-nullable control. Otherwise, the
* control will be nullable. Accepts a single generic argument, which is the type of the
* control's value.
*
* @param formState Initializes the control with an initial state value, or
* with an object that contains both a value and a disabled status.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or a `FormControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*
* @usageNotes
*
* ### Initialize a control as disabled
*
* The following example returns a control with an initial value in a disabled state.
*
* <code-example path="forms/ts/formBuilder/form_builder_example.ts" region="disabled-control">
* </code-example>
*/
| {
"end_byte": 13095,
"start_byte": 5189,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/form_builder.ts"
} |
angular/packages/forms/src/form_builder.ts_13098_20058 | trol<T>(
formState: T | FormControlState<T>,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): FormControl {
let newOptions: FormControlOptions = {};
if (!this.useNonNullable) {
return new FormControl(formState, validatorOrOpts, asyncValidator);
}
if (isAbstractControlOptions(validatorOrOpts)) {
// If the second argument is options, then they are copied.
newOptions = validatorOrOpts;
} else {
// If the other arguments are validators, they are copied into an options object.
newOptions.validators = validatorOrOpts;
newOptions.asyncValidators = asyncValidator;
}
return new FormControl<T>(formState, {...newOptions, nonNullable: true});
}
/**
* Constructs a new `FormArray` from the given array of configurations,
* validators and options. Accepts a single generic argument, which is the type of each control
* inside the array.
*
* @param controls An array of child controls or control configs. Each child control is given an
* index when it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of such functions, or an
* `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions.
*/
array<T>(
controls: Array<T>,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): FormArray<ɵElement<T, null>> {
const createdControls = controls.map((c) => this._createControl(c));
// Cast to `any` because the inferred types are not as specific as Element.
return new FormArray(createdControls, validatorOrOpts, asyncValidator) as any;
}
/** @internal */
_reduceControls<T>(controls: {
[k: string]: T | ControlConfig<T> | FormControlState<T> | AbstractControl<T>;
}): {[key: string]: AbstractControl} {
const createdControls: {[key: string]: AbstractControl} = {};
Object.keys(controls).forEach((controlName) => {
createdControls[controlName] = this._createControl(controls[controlName]);
});
return createdControls;
}
/** @internal */
_createControl<T>(
controls: T | FormControlState<T> | ControlConfig<T> | FormControl<T> | AbstractControl<T>,
): FormControl<T> | FormControl<T | null> | AbstractControl<T> {
if (controls instanceof FormControl) {
return controls as FormControl<T>;
} else if (controls instanceof AbstractControl) {
// A control; just return it
return controls;
} else if (Array.isArray(controls)) {
// ControlConfig Tuple
const value: T | FormControlState<T> = controls[0];
const validator: ValidatorFn | ValidatorFn[] | null =
controls.length > 1 ? controls[1]! : null;
const asyncValidator: AsyncValidatorFn | AsyncValidatorFn[] | null =
controls.length > 2 ? controls[2]! : null;
return this.control<T>(value, validator, asyncValidator);
} else {
// T or FormControlState<T>
return this.control<T>(controls);
}
}
}
/**
* @description
* `NonNullableFormBuilder` is similar to {@link FormBuilder}, but automatically constructed
* {@link FormControl} elements have `{nonNullable: true}` and are non-nullable.
*
* @publicApi
*/
@Injectable({
providedIn: 'root',
useFactory: () => inject(FormBuilder).nonNullable,
})
export abstract class NonNullableFormBuilder {
/**
* Similar to `FormBuilder#group`, except any implicitly constructed `FormControl`
* will be non-nullable (i.e. it will have `nonNullable` set to true). Note
* that already-constructed controls will not be altered.
*/
abstract group<T extends {}>(
controls: T,
options?: AbstractControlOptions | null,
): FormGroup<{[K in keyof T]: ɵElement<T[K], never>}>;
/**
* Similar to `FormBuilder#record`, except any implicitly constructed `FormControl`
* will be non-nullable (i.e. it will have `nonNullable` set to true). Note
* that already-constructed controls will not be altered.
*/
abstract record<T>(
controls: {[key: string]: T},
options?: AbstractControlOptions | null,
): FormRecord<ɵElement<T, never>>;
/**
* Similar to `FormBuilder#array`, except any implicitly constructed `FormControl`
* will be non-nullable (i.e. it will have `nonNullable` set to true). Note
* that already-constructed controls will not be altered.
*/
abstract array<T>(
controls: Array<T>,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): FormArray<ɵElement<T, never>>;
/**
* Similar to `FormBuilder#control`, except this overridden version of `control` forces
* `nonNullable` to be `true`, resulting in the control always being non-nullable.
*/
abstract control<T>(
formState: T | FormControlState<T>,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): FormControl<T>;
}
/**
* UntypedFormBuilder is the same as `FormBuilder`, but it provides untyped controls.
*/
@Injectable({providedIn: 'root'})
export class UntypedFormBuilder extends FormBuilder {
/**
* Like `FormBuilder#group`, except the resulting group is untyped.
*/
override group(
controlsConfig: {[key: string]: any},
options?: AbstractControlOptions | null,
): UntypedFormGroup;
/**
* @deprecated This API is not typesafe and can result in issues with Closure Compiler renaming.
* Use the `FormBuilder#group` overload with `AbstractControlOptions` instead.
*/
override group(
controlsConfig: {[key: string]: any},
options: {[key: string]: any},
): UntypedFormGroup;
override group(
controlsConfig: {[key: string]: any},
options: AbstractControlOptions | {[key: string]: any} | null = null,
): UntypedFormGroup {
return super.group(controlsConfig, options);
}
/**
* Like `FormBuilder#control`, except the resulting control is untyped.
*/
override control(
formState: any,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): UntypedFormControl {
return super.control(formState, validatorOrOpts, asyncValidator);
}
/**
* Like `FormBuilder#array`, except the resulting array is untyped.
*/
override array(
controlsConfig: any[],
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): UntypedFormArray {
return super.array(controlsConfig, validatorOrOpts, asyncValidator);
}
}
| {
"end_byte": 20058,
"start_byte": 13098,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/form_builder.ts"
} |
angular/packages/forms/src/version.ts_0_416 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the forms package.
*/
import {Version} from '@angular/core';
/**
* @publicApi
*/
export const VERSION = new Version('0.0.0-PLACEHOLDER');
| {
"end_byte": 416,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/version.ts"
} |
angular/packages/forms/src/directives/reactive_errors.ts_0_5511 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵRuntimeError as RuntimeError} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
import {
formArrayNameExample,
formControlNameExample,
formGroupNameExample,
ngModelGroupExample,
} from './error_examples';
export function controlParentException(nameOrIndex: string | number | null): Error {
return new RuntimeError(
RuntimeErrorCode.FORM_CONTROL_NAME_MISSING_PARENT,
`formControlName must be used with a parent formGroup directive. You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).
${describeFormControl(nameOrIndex)}
Example:
${formControlNameExample}`,
);
}
function describeFormControl(nameOrIndex: string | number | null): string {
if (nameOrIndex == null || nameOrIndex === '') {
return '';
}
const valueType = typeof nameOrIndex === 'string' ? 'name' : 'index';
return `Affected Form Control ${valueType}: "${nameOrIndex}"`;
}
export function ngModelGroupException(): Error {
return new RuntimeError(
RuntimeErrorCode.FORM_CONTROL_NAME_INSIDE_MODEL_GROUP,
`formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents
that also have a "form" prefix: formGroupName, formArrayName, or formGroup.
Option 1: Update the parent to be formGroupName (reactive form strategy)
${formGroupNameExample}
Option 2: Use ngModel instead of formControlName (template-driven strategy)
${ngModelGroupExample}`,
);
}
export function missingFormException(): Error {
return new RuntimeError(
RuntimeErrorCode.FORM_GROUP_MISSING_INSTANCE,
`formGroup expects a FormGroup instance. Please pass one in.
Example:
${formControlNameExample}`,
);
}
export function groupParentException(): Error {
return new RuntimeError(
RuntimeErrorCode.FORM_GROUP_NAME_MISSING_PARENT,
`formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).
Example:
${formGroupNameExample}`,
);
}
export function arrayParentException(): Error {
return new RuntimeError(
RuntimeErrorCode.FORM_ARRAY_NAME_MISSING_PARENT,
`formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).
Example:
${formArrayNameExample}`,
);
}
export const disabledAttrWarning = `
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
you. We recommend using this approach to avoid 'changed after checked' errors.
Example:
// Specify the \`disabled\` property at control creation time:
form = new FormGroup({
first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
// Controls can also be enabled/disabled after creation:
form.get('first')?.enable();
form.get('last')?.disable();
`;
export const asyncValidatorsDroppedWithOptsWarning = `
It looks like you're constructing using a FormControl with both an options argument and an
async validators argument. Mixing these arguments will cause your async validators to be dropped.
You should either put all your validators in the options object, or in separate validators
arguments. For example:
// Using validators arguments
fc = new FormControl(42, Validators.required, myAsyncValidator);
// Using AbstractControlOptions
fc = new FormControl(42, {validators: Validators.required, asyncValidators: myAV});
// Do NOT mix them: async validators will be dropped!
fc = new FormControl(42, {validators: Validators.required}, /* Oops! */ myAsyncValidator);
`;
export function ngModelWarning(directiveName: string): string {
return `
It looks like you're using ngModel on the same form field as ${directiveName}.
Support for using the ngModel input property and ngModelChange event with
reactive form directives has been deprecated in Angular v6 and will be removed
in a future version of Angular.
For more information on this, see our API docs here:
https://angular.io/api/forms/${
directiveName === 'formControl' ? 'FormControlDirective' : 'FormControlName'
}#use-with-ngmodel
`;
}
function describeKey(isFormGroup: boolean, key: string | number): string {
return isFormGroup ? `with name: '${key}'` : `at index: ${key}`;
}
export function noControlsError(isFormGroup: boolean): string {
return `
There are no form controls registered with this ${
isFormGroup ? 'group' : 'array'
} yet. If you're using ngModel,
you may want to check next tick (e.g. use setTimeout).
`;
}
export function missingControlError(isFormGroup: boolean, key: string | number): string {
return `Cannot find form control ${describeKey(isFormGroup, key)}`;
}
export function missingControlValueError(isFormGroup: boolean, key: string | number): string {
return `Must supply a value for form control ${describeKey(isFormGroup, key)}`;
}
| {
"end_byte": 5511,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/reactive_errors.ts"
} |
angular/packages/forms/src/directives/ng_no_validate_directive.ts_0_827 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive} from '@angular/core';
/**
* @description
*
* Adds `novalidate` attribute to all forms by default.
*
* `novalidate` is used to disable browser's native form validation.
*
* If you want to use native validation with Angular forms, just add `ngNativeValidate` attribute:
*
* ```
* <form ngNativeValidate></form>
* ```
*
* @publicApi
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
*/
@Directive({
selector: 'form:not([ngNoForm]):not([ngNativeValidate])',
host: {'novalidate': ''},
standalone: false,
})
export class ɵNgNoValidate {}
export {ɵNgNoValidate as NgNoValidate};
| {
"end_byte": 827,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/ng_no_validate_directive.ts"
} |
angular/packages/forms/src/directives/ng_control_status.ts_0_3952 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, Optional, Self, ɵWritable as Writable} from '@angular/core';
import {AbstractControlDirective} from './abstract_control_directive';
import {ControlContainer} from './control_container';
import {NgControl} from './ng_control';
import {type NgForm} from './ng_form';
import {type FormGroupDirective} from './reactive_directives/form_group_directive';
// DO NOT REFACTOR!
// Each status is represented by a separate function to make sure that
// advanced Closure Compiler optimizations related to property renaming
// can work correctly.
export class AbstractControlStatus {
private _cd: AbstractControlDirective | null;
constructor(cd: AbstractControlDirective | null) {
this._cd = cd;
}
protected get isTouched() {
// track the touched signal
this._cd?.control?._touched?.();
return !!this._cd?.control?.touched;
}
protected get isUntouched() {
return !!this._cd?.control?.untouched;
}
protected get isPristine() {
// track the pristine signal
this._cd?.control?._pristine?.();
return !!this._cd?.control?.pristine;
}
protected get isDirty() {
// pristine signal already tracked above
return !!this._cd?.control?.dirty;
}
protected get isValid() {
// track the status signal
this._cd?.control?._status?.();
return !!this._cd?.control?.valid;
}
protected get isInvalid() {
// status signal already tracked above
return !!this._cd?.control?.invalid;
}
protected get isPending() {
// status signal already tracked above
return !!this._cd?.control?.pending;
}
protected get isSubmitted() {
// track the submitted signal
(this._cd as Writable<NgForm | FormGroupDirective> | null)?._submitted?.();
// We check for the `submitted` field from `NgForm` and `FormGroupDirective` classes, but
// we avoid instanceof checks to prevent non-tree-shakable references to those types.
return !!(this._cd as Writable<NgForm | FormGroupDirective> | null)?.submitted;
}
}
export const ngControlStatusHost = {
'[class.ng-untouched]': 'isUntouched',
'[class.ng-touched]': 'isTouched',
'[class.ng-pristine]': 'isPristine',
'[class.ng-dirty]': 'isDirty',
'[class.ng-valid]': 'isValid',
'[class.ng-invalid]': 'isInvalid',
'[class.ng-pending]': 'isPending',
};
export const ngGroupStatusHost = {
...ngControlStatusHost,
'[class.ng-submitted]': 'isSubmitted',
};
/**
* @description
* Directive automatically applied to Angular form controls that sets CSS classes
* based on control status.
*
* @usageNotes
*
* ### CSS classes applied
*
* The following classes are applied as the properties become true:
*
* * ng-valid
* * ng-invalid
* * ng-pending
* * ng-pristine
* * ng-dirty
* * ng-untouched
* * ng-touched
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector: '[formControlName],[ngModel],[formControl]',
host: ngControlStatusHost,
standalone: false,
})
export class NgControlStatus extends AbstractControlStatus {
constructor(@Self() cd: NgControl) {
super(cd);
}
}
/**
* @description
* Directive automatically applied to Angular form groups that sets CSS classes
* based on control status (valid/invalid/dirty/etc). On groups, this includes the additional
* class ng-submitted.
*
* @see {@link NgControlStatus}
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]',
host: ngGroupStatusHost,
standalone: false,
})
export class NgControlStatusGroup extends AbstractControlStatus {
constructor(@Optional() @Self() cd: ControlContainer) {
super(cd);
}
}
| {
"end_byte": 3952,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/ng_control_status.ts"
} |
angular/packages/forms/src/directives/ng_control.ts_0_1184 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AbstractControlDirective} from './abstract_control_directive';
import {ControlContainer} from './control_container';
import {ControlValueAccessor} from './control_value_accessor';
/**
* @description
* A base class that all `FormControl`-based directives extend. It binds a `FormControl`
* object to a DOM element.
*
* @publicApi
*/
export abstract class NgControl extends AbstractControlDirective {
/**
* @description
* The parent form for the control.
*
* @internal
*/
_parent: ControlContainer | null = null;
/**
* @description
* The name for the control
*/
name: string | number | null = null;
/**
* @description
* The value accessor for the control
*/
valueAccessor: ControlValueAccessor | null = null;
/**
* @description
* The callback method to update the model from the view when requested
*
* @param newValue The new value for the view
*/
abstract viewToModelUpdate(newValue: any): void;
}
| {
"end_byte": 1184,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/ng_control.ts"
} |
angular/packages/forms/src/directives/select_multiple_control_value_accessor.ts_0_7983 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
ElementRef,
forwardRef,
Host,
Input,
OnDestroy,
Optional,
Provider,
Renderer2,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
import {
BuiltInControlValueAccessor,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
} from './control_value_accessor';
const SELECT_MULTIPLE_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectMultipleControlValueAccessor),
multi: true,
};
function _buildValueString(id: string, value: any): string {
if (id == null) return `${value}`;
if (typeof value === 'string') value = `'${value}'`;
if (value && typeof value === 'object') value = 'Object';
return `${id}: ${value}`.slice(0, 50);
}
function _extractId(valueString: string): string {
return valueString.split(':')[0];
}
/** Mock interface for HTML Options */
interface HTMLOption {
value: string;
selected: boolean;
}
/** Mock interface for HTMLCollection */
abstract class HTMLCollection {
// TODO(issue/24571): remove '!'.
length!: number;
abstract item(_: number): HTMLOption;
}
/**
* @description
* The `ControlValueAccessor` for writing multi-select control values and listening to multi-select
* control changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* @see {@link SelectControlValueAccessor}
*
* @usageNotes
*
* ### Using a multi-select control
*
* The follow example shows you how to use a multi-select control with a reactive form.
*
* ```ts
* const countryControl = new FormControl();
* ```
*
* ```
* <select multiple name="countries" [formControl]="countryControl">
* <option *ngFor="let country of countries" [ngValue]="country">
* {{ country.name }}
* </option>
* </select>
* ```
*
* ### Customizing option selection
*
* To customize the default option comparison algorithm, `<select>` supports `compareWith` input.
* See the `SelectControlValueAccessor` for usage.
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]',
host: {'(change)': 'onChange($event.target)', '(blur)': 'onTouched()'},
providers: [SELECT_MULTIPLE_VALUE_ACCESSOR],
standalone: false,
})
export class SelectMultipleControlValueAccessor
extends BuiltInControlValueAccessor
implements ControlValueAccessor
{
/**
* The current value.
* @nodoc
*/
value: any;
/** @internal */
_optionMap: Map<string, ɵNgSelectMultipleOption> = new Map<string, ɵNgSelectMultipleOption>();
/** @internal */
_idCounter: number = 0;
/**
* @description
* Tracks the option comparison algorithm for tracking identities when
* checking for changes.
*/
@Input()
set compareWith(fn: (o1: any, o2: any) => boolean) {
if (typeof fn !== 'function' && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw new RuntimeError(
RuntimeErrorCode.COMPAREWITH_NOT_A_FN,
`compareWith must be a function, but received ${JSON.stringify(fn)}`,
);
}
this._compareWith = fn;
}
private _compareWith: (o1: any, o2: any) => boolean = Object.is;
/**
* Sets the "value" property on one or of more of the select's options.
* @nodoc
*/
writeValue(value: any): void {
this.value = value;
let optionSelectedStateSetter: (opt: ɵNgSelectMultipleOption, o: any) => void;
if (Array.isArray(value)) {
// convert values to ids
const ids = value.map((v) => this._getOptionId(v));
optionSelectedStateSetter = (opt, o) => {
opt._setSelected(ids.indexOf(o.toString()) > -1);
};
} else {
optionSelectedStateSetter = (opt, o) => {
opt._setSelected(false);
};
}
this._optionMap.forEach(optionSelectedStateSetter);
}
/**
* Registers a function called when the control value changes
* and writes an array of the selected options.
* @nodoc
*/
override registerOnChange(fn: (value: any) => any): void {
this.onChange = (element: HTMLSelectElement) => {
const selected: Array<any> = [];
const selectedOptions = element.selectedOptions;
if (selectedOptions !== undefined) {
const options = selectedOptions;
for (let i = 0; i < options.length; i++) {
const opt = options[i];
const val = this._getOptionValue(opt.value);
selected.push(val);
}
}
// Degrade to use `options` when `selectedOptions` property is not available.
// Note: the `selectedOptions` is available in all supported browsers, but the Domino lib
// doesn't have it currently, see https://github.com/fgnass/domino/issues/177.
else {
const options = element.options;
for (let i = 0; i < options.length; i++) {
const opt = options[i];
if (opt.selected) {
const val = this._getOptionValue(opt.value);
selected.push(val);
}
}
}
this.value = selected;
fn(selected);
};
}
/** @internal */
_registerOption(value: ɵNgSelectMultipleOption): string {
const id: string = (this._idCounter++).toString();
this._optionMap.set(id, value);
return id;
}
/** @internal */
_getOptionId(value: any): string | null {
for (const id of this._optionMap.keys()) {
if (this._compareWith(this._optionMap.get(id)!._value, value)) return id;
}
return null;
}
/** @internal */
_getOptionValue(valueString: string): any {
const id: string = _extractId(valueString);
return this._optionMap.has(id) ? this._optionMap.get(id)!._value : valueString;
}
}
/**
* @description
* Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* @see {@link SelectMultipleControlValueAccessor}
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector: 'option',
standalone: false,
})
export class ɵNgSelectMultipleOption implements OnDestroy {
// TODO(issue/24571): remove '!'.
id!: string;
/** @internal */
_value: any;
constructor(
private _element: ElementRef,
private _renderer: Renderer2,
@Optional() @Host() private _select: SelectMultipleControlValueAccessor,
) {
if (this._select) {
this.id = this._select._registerOption(this);
}
}
/**
* @description
* Tracks the value bound to the option element. Unlike the value binding,
* ngValue supports binding to objects.
*/
@Input('ngValue')
set ngValue(value: any) {
if (this._select == null) return;
this._value = value;
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
}
/**
* @description
* Tracks simple string values bound to the option element.
* For objects, use the `ngValue` input binding.
*/
@Input('value')
set value(value: any) {
if (this._select) {
this._value = value;
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
} else {
this._setElementValue(value);
}
}
/** @internal */
_setElementValue(value: string): void {
this._renderer.setProperty(this._element.nativeElement, 'value', value);
}
/** @internal */
_setSelected(selected: boolean) {
this._renderer.setProperty(this._element.nativeElement, 'selected', selected);
}
/** @nodoc */
ngOnDestroy(): void {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
}
}
export {ɵNgSelectMultipleOption as NgSelectMultipleOption};
| {
"end_byte": 7983,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/select_multiple_control_value_accessor.ts"
} |
angular/packages/forms/src/directives/abstract_form_group_directive.ts_0_1866 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, OnDestroy, OnInit} from '@angular/core';
import {FormGroup} from '../model/form_group';
import {ControlContainer} from './control_container';
import type {Form} from './form_interface';
import {controlPath} from './shared';
/**
* @description
* A base class for code shared between the `NgModelGroup` and `FormGroupName` directives.
*
* @publicApi
*/
@Directive({
standalone: false,
})
export class AbstractFormGroupDirective extends ControlContainer implements OnInit, OnDestroy {
/**
* @description
* The parent control for the group
*
* @internal
*/
// TODO(issue/24571): remove '!'.
_parent!: ControlContainer;
/** @nodoc */
ngOnInit(): void {
this._checkParentType();
// Register the group with its parent group.
this.formDirective!.addFormGroup(this);
}
/** @nodoc */
ngOnDestroy(): void {
if (this.formDirective) {
// Remove the group from its parent group.
this.formDirective.removeFormGroup(this);
}
}
/**
* @description
* The `FormGroup` bound to this directive.
*/
override get control(): FormGroup {
return this.formDirective!.getFormGroup(this);
}
/**
* @description
* The path to this group from the top-level directive.
*/
override get path(): string[] {
return controlPath(this.name == null ? this.name : this.name.toString(), this._parent);
}
/**
* @description
* The top-level directive for this group if present, otherwise null.
*/
override get formDirective(): Form | null {
return this._parent ? this._parent.formDirective : null;
}
/** @internal */
_checkParentType(): void {}
}
| {
"end_byte": 1866,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/abstract_form_group_directive.ts"
} |
angular/packages/forms/src/directives/control_container.ts_0_952 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AbstractControlDirective} from './abstract_control_directive';
import type {Form} from './form_interface';
/**
* @description
* A base class for directives that contain multiple registered instances of `NgControl`.
* Only used by the forms module.
*
* @publicApi
*/
export abstract class ControlContainer extends AbstractControlDirective {
/**
* @description
* The name for the control
*/
// TODO(issue/24571): remove '!'.
name!: string | number | null;
/**
* @description
* The top-level form directive for the control.
*/
get formDirective(): Form | null {
return null;
}
/**
* @description
* The path to this group.
*/
override get path(): string[] | null {
return null;
}
}
| {
"end_byte": 952,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/control_container.ts"
} |
angular/packages/forms/src/directives/abstract_control_directive.ts_0_659 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable} from 'rxjs';
import {AbstractControl} from '../model/abstract_model';
import {composeAsyncValidators, composeValidators} from '../validators';
import {
AsyncValidator,
AsyncValidatorFn,
ValidationErrors,
Validator,
ValidatorFn,
} from './validators';
/**
* @description
* Base class for control directives.
*
* This class is only used internally in the `ReactiveFormsModule` and the `FormsModule`.
*
* @publicApi
*/ | {
"end_byte": 659,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/abstract_control_directive.ts"
} |
angular/packages/forms/src/directives/abstract_control_directive.ts_660_9136 | export abstract class AbstractControlDirective {
/**
* @description
* A reference to the underlying control.
*
* @returns the control that backs this directive. Most properties fall through to that instance.
*/
abstract get control(): AbstractControl | null;
/**
* @description
* Reports the value of the control if it is present, otherwise null.
*/
get value(): any {
return this.control ? this.control.value : null;
}
/**
* @description
* Reports whether the control is valid. A control is considered valid if no
* validation errors exist with the current value.
* If the control is not present, null is returned.
*/
get valid(): boolean | null {
return this.control ? this.control.valid : null;
}
/**
* @description
* Reports whether the control is invalid, meaning that an error exists in the input value.
* If the control is not present, null is returned.
*/
get invalid(): boolean | null {
return this.control ? this.control.invalid : null;
}
/**
* @description
* Reports whether a control is pending, meaning that async validation is occurring and
* errors are not yet available for the input value. If the control is not present, null is
* returned.
*/
get pending(): boolean | null {
return this.control ? this.control.pending : null;
}
/**
* @description
* Reports whether the control is disabled, meaning that the control is disabled
* in the UI and is exempt from validation checks and excluded from aggregate
* values of ancestor controls. If the control is not present, null is returned.
*/
get disabled(): boolean | null {
return this.control ? this.control.disabled : null;
}
/**
* @description
* Reports whether the control is enabled, meaning that the control is included in ancestor
* calculations of validity or value. If the control is not present, null is returned.
*/
get enabled(): boolean | null {
return this.control ? this.control.enabled : null;
}
/**
* @description
* Reports the control's validation errors. If the control is not present, null is returned.
*/
get errors(): ValidationErrors | null {
return this.control ? this.control.errors : null;
}
/**
* @description
* Reports whether the control is pristine, meaning that the user has not yet changed
* the value in the UI. If the control is not present, null is returned.
*/
get pristine(): boolean | null {
return this.control ? this.control.pristine : null;
}
/**
* @description
* Reports whether the control is dirty, meaning that the user has changed
* the value in the UI. If the control is not present, null is returned.
*/
get dirty(): boolean | null {
return this.control ? this.control.dirty : null;
}
/**
* @description
* Reports whether the control is touched, meaning that the user has triggered
* a `blur` event on it. If the control is not present, null is returned.
*/
get touched(): boolean | null {
return this.control ? this.control.touched : null;
}
/**
* @description
* Reports the validation status of the control. Possible values include:
* 'VALID', 'INVALID', 'DISABLED', and 'PENDING'.
* If the control is not present, null is returned.
*/
get status(): string | null {
return this.control ? this.control.status : null;
}
/**
* @description
* Reports whether the control is untouched, meaning that the user has not yet triggered
* a `blur` event on it. If the control is not present, null is returned.
*/
get untouched(): boolean | null {
return this.control ? this.control.untouched : null;
}
/**
* @description
* Returns a multicasting observable that emits a validation status whenever it is
* calculated for the control. If the control is not present, null is returned.
*/
get statusChanges(): Observable<any> | null {
return this.control ? this.control.statusChanges : null;
}
/**
* @description
* Returns a multicasting observable of value changes for the control that emits every time the
* value of the control changes in the UI or programmatically.
* If the control is not present, null is returned.
*/
get valueChanges(): Observable<any> | null {
return this.control ? this.control.valueChanges : null;
}
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
get path(): string[] | null {
return null;
}
/**
* Contains the result of merging synchronous validators into a single validator function
* (combined using `Validators.compose`).
*/
private _composedValidatorFn: ValidatorFn | null | undefined;
/**
* Contains the result of merging asynchronous validators into a single validator function
* (combined using `Validators.composeAsync`).
*/
private _composedAsyncValidatorFn: AsyncValidatorFn | null | undefined;
/**
* Set of synchronous validators as they were provided while calling `setValidators` function.
* @internal
*/
_rawValidators: Array<Validator | ValidatorFn> = [];
/**
* Set of asynchronous validators as they were provided while calling `setAsyncValidators`
* function.
* @internal
*/
_rawAsyncValidators: Array<AsyncValidator | AsyncValidatorFn> = [];
/**
* Sets synchronous validators for this directive.
* @internal
*/
_setValidators(validators: Array<Validator | ValidatorFn> | undefined): void {
this._rawValidators = validators || [];
this._composedValidatorFn = composeValidators(this._rawValidators);
}
/**
* Sets asynchronous validators for this directive.
* @internal
*/
_setAsyncValidators(validators: Array<AsyncValidator | AsyncValidatorFn> | undefined): void {
this._rawAsyncValidators = validators || [];
this._composedAsyncValidatorFn = composeAsyncValidators(this._rawAsyncValidators);
}
/**
* @description
* Synchronous validator function composed of all the synchronous validators registered with this
* directive.
*/
get validator(): ValidatorFn | null {
return this._composedValidatorFn || null;
}
/**
* @description
* Asynchronous validator function composed of all the asynchronous validators registered with
* this directive.
*/
get asyncValidator(): AsyncValidatorFn | null {
return this._composedAsyncValidatorFn || null;
}
/*
* The set of callbacks to be invoked when directive instance is being destroyed.
*/
private _onDestroyCallbacks: (() => void)[] = [];
/**
* Internal function to register callbacks that should be invoked
* when directive instance is being destroyed.
* @internal
*/
_registerOnDestroy(fn: () => void): void {
this._onDestroyCallbacks.push(fn);
}
/**
* Internal function to invoke all registered "on destroy" callbacks.
* Note: calling this function also clears the list of callbacks.
* @internal
*/
_invokeOnDestroyCallbacks(): void {
this._onDestroyCallbacks.forEach((fn) => fn());
this._onDestroyCallbacks = [];
}
/**
* @description
* Resets the control with the provided value if the control is present.
*/
reset(value: any = undefined): void {
if (this.control) this.control.reset(value);
}
/**
* @description
* Reports whether the control with the given path has the error specified.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* For example, for the following `FormGroup`:
*
* ```
* form = new FormGroup({
* address: new FormGroup({ street: new FormControl() })
* });
* ```
*
* The path to the 'street' control from the root form would be 'address' -> 'street'.
*
* It can be provided to this method in one of two formats:
*
* 1. An array of string control names, e.g. `['address', 'street']`
* 1. A period-delimited list of control names in one string, e.g. `'address.street'`
*
* If no path is given, this method checks for the error on the current control.
*
* @returns whether the given error is present in the control at the given path.
*
* If the control is not present, false is returned.
*/ | {
"end_byte": 9136,
"start_byte": 660,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/abstract_control_directive.ts"
} |
angular/packages/forms/src/directives/abstract_control_directive.ts_9139_10387 | hasError(errorCode: string, path?: Array<string | number> | string): boolean {
return this.control ? this.control.hasError(errorCode, path) : false;
}
/**
* @description
* Reports error data for the control with the given path.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* For example, for the following `FormGroup`:
*
* ```
* form = new FormGroup({
* address: new FormGroup({ street: new FormControl() })
* });
* ```
*
* The path to the 'street' control from the root form would be 'address' -> 'street'.
*
* It can be provided to this method in one of two formats:
*
* 1. An array of string control names, e.g. `['address', 'street']`
* 1. A period-delimited list of control names in one string, e.g. `'address.street'`
*
* @returns error data for that particular error. If the control or error is not present,
* null is returned.
*/
getError(errorCode: string, path?: Array<string | number> | string): any {
return this.control ? this.control.getError(errorCode, path) : null;
}
} | {
"end_byte": 10387,
"start_byte": 9139,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/abstract_control_directive.ts"
} |
angular/packages/forms/src/directives/number_value_accessor.ts_0_2086 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, ElementRef, forwardRef, Provider} from '@angular/core';
import {
BuiltInControlValueAccessor,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
} from './control_value_accessor';
const NUMBER_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NumberValueAccessor),
multi: true,
};
/**
* @description
* The `ControlValueAccessor` for writing a number value and listening to number input changes.
* The value accessor is used by the `FormControlDirective`, `FormControlName`, and `NgModel`
* directives.
*
* @usageNotes
*
* ### Using a number input with a reactive form.
*
* The following example shows how to use a number input with a reactive form.
*
* ```ts
* const totalCountControl = new FormControl();
* ```
*
* ```
* <input type="number" [formControl]="totalCountControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]',
host: {'(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},
providers: [NUMBER_VALUE_ACCESSOR],
standalone: false,
})
export class NumberValueAccessor
extends BuiltInControlValueAccessor
implements ControlValueAccessor
{
/**
* Sets the "value" property on the input element.
* @nodoc
*/
writeValue(value: number): void {
// The value needs to be normalized for IE9, otherwise it is set to 'null' when null
const normalizedValue = value == null ? '' : value;
this.setProperty('value', normalizedValue);
}
/**
* Registers a function called when the control value changes.
* @nodoc
*/
override registerOnChange(fn: (_: number | null) => void): void {
this.onChange = (value) => {
fn(value == '' ? null : parseFloat(value));
};
}
}
| {
"end_byte": 2086,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/number_value_accessor.ts"
} |
angular/packages/forms/src/directives/shared.ts_0_8860 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectionToken, ɵRuntimeError as RuntimeError} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
import type {AbstractControl} from '../model/abstract_model';
import type {FormArray} from '../model/form_array';
import type {FormControl} from '../model/form_control';
import type {FormGroup} from '../model/form_group';
import {getControlAsyncValidators, getControlValidators, mergeValidators} from '../validators';
import type {AbstractControlDirective} from './abstract_control_directive';
import type {AbstractFormGroupDirective} from './abstract_form_group_directive';
import type {ControlContainer} from './control_container';
import {BuiltInControlValueAccessor, ControlValueAccessor} from './control_value_accessor';
import {DefaultValueAccessor} from './default_value_accessor';
import type {NgControl} from './ng_control';
import type {FormArrayName} from './reactive_directives/form_group_name';
import {ngModelWarning} from './reactive_errors';
import {AsyncValidatorFn, Validator, ValidatorFn} from './validators';
/**
* Token to provide to allow SetDisabledState to always be called when a CVA is added, regardless of
* whether the control is disabled or enabled.
*
* @see {@link FormsModule#withconfig}
*/
export const CALL_SET_DISABLED_STATE = new InjectionToken('CallSetDisabledState', {
providedIn: 'root',
factory: () => setDisabledStateDefault,
});
/**
* The type for CALL_SET_DISABLED_STATE. If `always`, then ControlValueAccessor will always call
* `setDisabledState` when attached, which is the most correct behavior. Otherwise, it will only be
* called when disabled, which is the legacy behavior for compatibility.
*
* @publicApi
* @see {@link FormsModule#withconfig}
*/
export type SetDisabledStateOption = 'whenDisabledForLegacyCode' | 'always';
/**
* Whether to use the fixed setDisabledState behavior by default.
*/
export const setDisabledStateDefault: SetDisabledStateOption = 'always';
export function controlPath(name: string | null, parent: ControlContainer): string[] {
return [...parent.path!, name!];
}
/**
* Links a Form control and a Form directive by setting up callbacks (such as `onChange`) on both
* instances. This function is typically invoked when form directive is being initialized.
*
* @param control Form control instance that should be linked.
* @param dir Directive that should be linked with a given control.
*/
export function setUpControl(
control: FormControl,
dir: NgControl,
callSetDisabledState: SetDisabledStateOption = setDisabledStateDefault,
): void {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!control) _throwError(dir, 'Cannot find control with');
if (!dir.valueAccessor) _throwMissingValueAccessorError(dir);
}
setUpValidators(control, dir);
dir.valueAccessor!.writeValue(control.value);
// The legacy behavior only calls the CVA's `setDisabledState` if the control is disabled.
// If the `callSetDisabledState` option is set to `always`, then this bug is fixed and
// the method is always called.
if (control.disabled || callSetDisabledState === 'always') {
dir.valueAccessor!.setDisabledState?.(control.disabled);
}
setUpViewChangePipeline(control, dir);
setUpModelChangePipeline(control, dir);
setUpBlurPipeline(control, dir);
setUpDisabledChangeHandler(control, dir);
}
/**
* Reverts configuration performed by the `setUpControl` control function.
* Effectively disconnects form control with a given form directive.
* This function is typically invoked when corresponding form directive is being destroyed.
*
* @param control Form control which should be cleaned up.
* @param dir Directive that should be disconnected from a given control.
* @param validateControlPresenceOnChange Flag that indicates whether onChange handler should
* contain asserts to verify that it's not called once directive is destroyed. We need this flag
* to avoid potentially breaking changes caused by better control cleanup introduced in #39235.
*/
export function cleanUpControl(
control: FormControl | null,
dir: NgControl,
validateControlPresenceOnChange: boolean = true,
): void {
const noop = () => {
if (validateControlPresenceOnChange && (typeof ngDevMode === 'undefined' || ngDevMode)) {
_noControlError(dir);
}
};
// The `valueAccessor` field is typically defined on FromControl and FormControlName directive
// instances and there is a logic in `selectValueAccessor` function that throws if it's not the
// case. We still check the presence of `valueAccessor` before invoking its methods to make sure
// that cleanup works correctly if app code or tests are setup to ignore the error thrown from
// `selectValueAccessor`. See https://github.com/angular/angular/issues/40521.
if (dir.valueAccessor) {
dir.valueAccessor.registerOnChange(noop);
dir.valueAccessor.registerOnTouched(noop);
}
cleanUpValidators(control, dir);
if (control) {
dir._invokeOnDestroyCallbacks();
control._registerOnCollectionChange(() => {});
}
}
function registerOnValidatorChange<V>(validators: (V | Validator)[], onChange: () => void): void {
validators.forEach((validator: V | Validator) => {
if ((<Validator>validator).registerOnValidatorChange)
(<Validator>validator).registerOnValidatorChange!(onChange);
});
}
/**
* Sets up disabled change handler function on a given form control if ControlValueAccessor
* associated with a given directive instance supports the `setDisabledState` call.
*
* @param control Form control where disabled change handler should be setup.
* @param dir Corresponding directive instance associated with this control.
*/
export function setUpDisabledChangeHandler(control: FormControl, dir: NgControl): void {
if (dir.valueAccessor!.setDisabledState) {
const onDisabledChange = (isDisabled: boolean) => {
dir.valueAccessor!.setDisabledState!(isDisabled);
};
control.registerOnDisabledChange(onDisabledChange);
// Register a callback function to cleanup disabled change handler
// from a control instance when a directive is destroyed.
dir._registerOnDestroy(() => {
control._unregisterOnDisabledChange(onDisabledChange);
});
}
}
/**
* Sets up sync and async directive validators on provided form control.
* This function merges validators from the directive into the validators of the control.
*
* @param control Form control where directive validators should be setup.
* @param dir Directive instance that contains validators to be setup.
*/
export function setUpValidators(control: AbstractControl, dir: AbstractControlDirective): void {
const validators = getControlValidators(control);
if (dir.validator !== null) {
control.setValidators(mergeValidators<ValidatorFn>(validators, dir.validator));
} else if (typeof validators === 'function') {
// If sync validators are represented by a single validator function, we force the
// `Validators.compose` call to happen by executing the `setValidators` function with
// an array that contains that function. We need this to avoid possible discrepancies in
// validators behavior, so sync validators are always processed by the `Validators.compose`.
// Note: we should consider moving this logic inside the `setValidators` function itself, so we
// have consistent behavior on AbstractControl API level. The same applies to the async
// validators logic below.
control.setValidators([validators]);
}
const asyncValidators = getControlAsyncValidators(control);
if (dir.asyncValidator !== null) {
control.setAsyncValidators(
mergeValidators<AsyncValidatorFn>(asyncValidators, dir.asyncValidator),
);
} else if (typeof asyncValidators === 'function') {
control.setAsyncValidators([asyncValidators]);
}
// Re-run validation when validator binding changes, e.g. minlength=3 -> minlength=4
const onValidatorChange = () => control.updateValueAndValidity();
registerOnValidatorChange<ValidatorFn>(dir._rawValidators, onValidatorChange);
registerOnValidatorChange<AsyncValidatorFn>(dir._rawAsyncValidators, onValidatorChange);
}
/**
* Cleans up sync and async directive validators on provided form control.
* This function reverts the setup performed by the `setUpValidators` function, i.e.
* removes directive-specific validators from a given control instance.
*
* @param control Form control from where directive validators should be removed.
* @param dir Directive instance that contains validators to be removed.
* @returns true if a control was updated as a result of this action.
*/
| {
"end_byte": 8860,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/shared.ts"
} |
angular/packages/forms/src/directives/shared.ts_8861_17232 | xport function cleanUpValidators(
control: AbstractControl | null,
dir: AbstractControlDirective,
): boolean {
let isControlUpdated = false;
if (control !== null) {
if (dir.validator !== null) {
const validators = getControlValidators(control);
if (Array.isArray(validators) && validators.length > 0) {
// Filter out directive validator function.
const updatedValidators = validators.filter((validator) => validator !== dir.validator);
if (updatedValidators.length !== validators.length) {
isControlUpdated = true;
control.setValidators(updatedValidators);
}
}
}
if (dir.asyncValidator !== null) {
const asyncValidators = getControlAsyncValidators(control);
if (Array.isArray(asyncValidators) && asyncValidators.length > 0) {
// Filter out directive async validator function.
const updatedAsyncValidators = asyncValidators.filter(
(asyncValidator) => asyncValidator !== dir.asyncValidator,
);
if (updatedAsyncValidators.length !== asyncValidators.length) {
isControlUpdated = true;
control.setAsyncValidators(updatedAsyncValidators);
}
}
}
}
// Clear onValidatorChange callbacks by providing a noop function.
const noop = () => {};
registerOnValidatorChange<ValidatorFn>(dir._rawValidators, noop);
registerOnValidatorChange<AsyncValidatorFn>(dir._rawAsyncValidators, noop);
return isControlUpdated;
}
function setUpViewChangePipeline(control: FormControl, dir: NgControl): void {
dir.valueAccessor!.registerOnChange((newValue: any) => {
control._pendingValue = newValue;
control._pendingChange = true;
control._pendingDirty = true;
if (control.updateOn === 'change') updateControl(control, dir);
});
}
function setUpBlurPipeline(control: FormControl, dir: NgControl): void {
dir.valueAccessor!.registerOnTouched(() => {
control._pendingTouched = true;
if (control.updateOn === 'blur' && control._pendingChange) updateControl(control, dir);
if (control.updateOn !== 'submit') control.markAsTouched();
});
}
function updateControl(control: FormControl, dir: NgControl): void {
if (control._pendingDirty) control.markAsDirty();
control.setValue(control._pendingValue, {emitModelToViewChange: false});
dir.viewToModelUpdate(control._pendingValue);
control._pendingChange = false;
}
function setUpModelChangePipeline(control: FormControl, dir: NgControl): void {
const onChange = (newValue?: any, emitModelEvent?: boolean) => {
// control -> view
dir.valueAccessor!.writeValue(newValue);
// control -> ngModel
if (emitModelEvent) dir.viewToModelUpdate(newValue);
};
control.registerOnChange(onChange);
// Register a callback function to cleanup onChange handler
// from a control instance when a directive is destroyed.
dir._registerOnDestroy(() => {
control._unregisterOnChange(onChange);
});
}
/**
* Links a FormGroup or FormArray instance and corresponding Form directive by setting up validators
* present in the view.
*
* @param control FormGroup or FormArray instance that should be linked.
* @param dir Directive that provides view validators.
*/
export function setUpFormContainer(
control: FormGroup | FormArray,
dir: AbstractFormGroupDirective | FormArrayName,
) {
if (control == null && (typeof ngDevMode === 'undefined' || ngDevMode))
_throwError(dir, 'Cannot find control with');
setUpValidators(control, dir);
}
/**
* Reverts the setup performed by the `setUpFormContainer` function.
*
* @param control FormGroup or FormArray instance that should be cleaned up.
* @param dir Directive that provided view validators.
* @returns true if a control was updated as a result of this action.
*/
export function cleanUpFormContainer(
control: FormGroup | FormArray,
dir: AbstractFormGroupDirective | FormArrayName,
): boolean {
return cleanUpValidators(control, dir);
}
function _noControlError(dir: NgControl) {
return _throwError(dir, 'There is no FormControl instance attached to form control element with');
}
function _throwError(dir: AbstractControlDirective, message: string): void {
const messageEnd = _describeControlLocation(dir);
throw new Error(`${message} ${messageEnd}`);
}
function _describeControlLocation(dir: AbstractControlDirective): string {
const path = dir.path;
if (path && path.length > 1) return `path: '${path.join(' -> ')}'`;
if (path?.[0]) return `name: '${path}'`;
return 'unspecified name attribute';
}
function _throwMissingValueAccessorError(dir: AbstractControlDirective) {
const loc = _describeControlLocation(dir);
throw new RuntimeError(
RuntimeErrorCode.NG_MISSING_VALUE_ACCESSOR,
`No value accessor for form control ${loc}.`,
);
}
function _throwInvalidValueAccessorError(dir: AbstractControlDirective) {
const loc = _describeControlLocation(dir);
throw new RuntimeError(
RuntimeErrorCode.NG_VALUE_ACCESSOR_NOT_PROVIDED,
`Value accessor was not provided as an array for form control with ${loc}. ` +
`Check that the \`NG_VALUE_ACCESSOR\` token is configured as a \`multi: true\` provider.`,
);
}
export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean {
if (!changes.hasOwnProperty('model')) return false;
const change = changes['model'];
if (change.isFirstChange()) return true;
return !Object.is(viewModel, change.currentValue);
}
export function isBuiltInAccessor(valueAccessor: ControlValueAccessor): boolean {
// Check if a given value accessor is an instance of a class that directly extends
// `BuiltInControlValueAccessor` one.
return Object.getPrototypeOf(valueAccessor.constructor) === BuiltInControlValueAccessor;
}
export function syncPendingControls(
form: FormGroup,
directives: Set<NgControl> | NgControl[],
): void {
form._syncPendingControls();
directives.forEach((dir: NgControl) => {
const control = dir.control as FormControl;
if (control.updateOn === 'submit' && control._pendingChange) {
dir.viewToModelUpdate(control._pendingValue);
control._pendingChange = false;
}
});
}
// TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented
export function selectValueAccessor(
dir: NgControl,
valueAccessors: ControlValueAccessor[],
): ControlValueAccessor | null {
if (!valueAccessors) return null;
if (!Array.isArray(valueAccessors) && (typeof ngDevMode === 'undefined' || ngDevMode))
_throwInvalidValueAccessorError(dir);
let defaultAccessor: ControlValueAccessor | undefined = undefined;
let builtinAccessor: ControlValueAccessor | undefined = undefined;
let customAccessor: ControlValueAccessor | undefined = undefined;
valueAccessors.forEach((v: ControlValueAccessor) => {
if (v.constructor === DefaultValueAccessor) {
defaultAccessor = v;
} else if (isBuiltInAccessor(v)) {
if (builtinAccessor && (typeof ngDevMode === 'undefined' || ngDevMode))
_throwError(dir, 'More than one built-in value accessor matches form control with');
builtinAccessor = v;
} else {
if (customAccessor && (typeof ngDevMode === 'undefined' || ngDevMode))
_throwError(dir, 'More than one custom value accessor matches form control with');
customAccessor = v;
}
});
if (customAccessor) return customAccessor;
if (builtinAccessor) return builtinAccessor;
if (defaultAccessor) return defaultAccessor;
if (typeof ngDevMode === 'undefined' || ngDevMode) {
_throwError(dir, 'No valid value accessor for form control with');
}
return null;
}
export function removeListItem<T>(list: T[], el: T): void {
const index = list.indexOf(el);
if (index > -1) list.splice(index, 1);
}
// TODO(kara): remove after deprecation period
export function _ngModelWarning(
name: string,
type: {_ngModelWarningSentOnce: boolean},
instance: {_ngModelWarningSent: boolean},
warningConfig: string | null,
) {
if (warningConfig === 'never') return;
if (
((warningConfig === null || warningConfig === 'once') && !type._ngModelWarningSentOnce) ||
(warningConfig === 'always' && !instance._ngModelWarningSent)
) {
console.warn(ngModelWarning(name));
type._ngModelWarningSentOnce = true;
instance._ngModelWarningSent = true;
}
}
| {
"end_byte": 17232,
"start_byte": 8861,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/shared.ts"
} |
angular/packages/forms/src/directives/range_value_accessor.ts_0_1964 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, forwardRef, Provider} from '@angular/core';
import {
BuiltInControlValueAccessor,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
} from './control_value_accessor';
const RANGE_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RangeValueAccessor),
multi: true,
};
/**
* @description
* The `ControlValueAccessor` for writing a range value and listening to range input changes.
* The value accessor is used by the `FormControlDirective`, `FormControlName`, and `NgModel`
* directives.
*
* @usageNotes
*
* ### Using a range input with a reactive form
*
* The following example shows how to use a range input with a reactive form.
*
* ```ts
* const ageControl = new FormControl();
* ```
*
* ```
* <input type="range" [formControl]="ageControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]',
host: {
'(change)': 'onChange($event.target.value)',
'(input)': 'onChange($event.target.value)',
'(blur)': 'onTouched()',
},
providers: [RANGE_VALUE_ACCESSOR],
standalone: false,
})
export class RangeValueAccessor
extends BuiltInControlValueAccessor
implements ControlValueAccessor
{
/**
* Sets the "value" property on the input element.
* @nodoc
*/
writeValue(value: any): void {
this.setProperty('value', parseFloat(value));
}
/**
* Registers a function called when the control value changes.
* @nodoc
*/
override registerOnChange(fn: (_: number | null) => void): void {
this.onChange = (value) => {
fn(value == '' ? null : parseFloat(value));
};
}
}
| {
"end_byte": 1964,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/range_value_accessor.ts"
} |
angular/packages/forms/src/directives/form_interface.ts_0_2036 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {FormControl} from '../model/form_control';
import {FormGroup} from '../model/form_group';
import {AbstractFormGroupDirective} from './abstract_form_group_directive';
import {NgControl} from './ng_control';
/**
* @description
* An interface implemented by `FormGroupDirective` and `NgForm` directives.
*
* Only used by the `ReactiveFormsModule` and `FormsModule`.
*
* @publicApi
*/
export interface Form {
/**
* @description
* Add a control to this form.
*
* @param dir The control directive to add to the form.
*/
addControl(dir: NgControl): void;
/**
* @description
* Remove a control from this form.
*
* @param dir: The control directive to remove from the form.
*/
removeControl(dir: NgControl): void;
/**
* @description
* The control directive from which to get the `FormControl`.
*
* @param dir: The control directive.
*/
getControl(dir: NgControl): FormControl;
/**
* @description
* Add a group of controls to this form.
*
* @param dir: The control group directive to add.
*/
addFormGroup(dir: AbstractFormGroupDirective): void;
/**
* @description
* Remove a group of controls to this form.
*
* @param dir: The control group directive to remove.
*/
removeFormGroup(dir: AbstractFormGroupDirective): void;
/**
* @description
* The `FormGroup` associated with a particular `AbstractFormGroupDirective`.
*
* @param dir: The form group directive from which to get the `FormGroup`.
*/
getFormGroup(dir: AbstractFormGroupDirective): FormGroup;
/**
* @description
* Update the model for a particular control with a new value.
*
* @param dir: The control directive to update.
* @param value: The new value for the control.
*/
updateModel(dir: NgControl, value: any): void;
}
| {
"end_byte": 2036,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/form_interface.ts"
} |
angular/packages/forms/src/directives/control_value_accessor.ts_0_6061 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, ElementRef, InjectionToken, Renderer2} from '@angular/core';
/**
* @description
* Defines an interface that acts as a bridge between the Angular forms API and a
* native element in the DOM.
*
* Implement this interface to create a custom form control directive
* that integrates with Angular forms.
*
* @see {@link DefaultValueAccessor}
*
* @publicApi
*/
export interface ControlValueAccessor {
/**
* @description
* Writes a new value to the element.
*
* This method is called by the forms API to write to the view when programmatic
* changes from model to view are requested.
*
* @usageNotes
* ### Write a value to the element
*
* The following example writes a value to the native DOM element.
*
* ```ts
* writeValue(value: any): void {
* this._renderer.setProperty(this._elementRef.nativeElement, 'value', value);
* }
* ```
*
* @param obj The new value for the element
*/
writeValue(obj: any): void;
/**
* @description
* Registers a callback function that is called when the control's value
* changes in the UI.
*
* This method is called by the forms API on initialization to update the form
* model when values propagate from the view to the model.
*
* When implementing the `registerOnChange` method in your own value accessor,
* save the given function so your class calls it at the appropriate time.
*
* @usageNotes
* ### Store the change function
*
* The following example stores the provided function as an internal method.
*
* ```ts
* registerOnChange(fn: (_: any) => void): void {
* this._onChange = fn;
* }
* ```
*
* When the value changes in the UI, call the registered
* function to allow the forms API to update itself:
*
* ```ts
* host: {
* '(change)': '_onChange($event.target.value)'
* }
* ```
*
* @param fn The callback function to register
*/
registerOnChange(fn: any): void;
/**
* @description
* Registers a callback function that is called by the forms API on initialization
* to update the form model on blur.
*
* When implementing `registerOnTouched` in your own value accessor, save the given
* function so your class calls it when the control should be considered
* blurred or "touched".
*
* @usageNotes
* ### Store the callback function
*
* The following example stores the provided function as an internal method.
*
* ```ts
* registerOnTouched(fn: any): void {
* this._onTouched = fn;
* }
* ```
*
* On blur (or equivalent), your class should call the registered function to allow
* the forms API to update itself:
*
* ```ts
* host: {
* '(blur)': '_onTouched()'
* }
* ```
*
* @param fn The callback function to register
*/
registerOnTouched(fn: any): void;
/**
* @description
* Function that is called by the forms API when the control status changes to
* or from 'DISABLED'. Depending on the status, it enables or disables the
* appropriate DOM element.
*
* @usageNotes
* The following is an example of writing the disabled property to a native DOM element:
*
* ```ts
* setDisabledState(isDisabled: boolean): void {
* this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
* }
* ```
*
* @param isDisabled The disabled status to set on the element
*/
setDisabledState?(isDisabled: boolean): void;
}
/**
* Base class for all ControlValueAccessor classes defined in Forms package.
* Contains common logic and utility functions.
*
* Note: this is an *internal-only* class and should not be extended or used directly in
* applications code.
*/
@Directive()
export class BaseControlValueAccessor {
/**
* The registered callback function called when a change or input event occurs on the input
* element.
* @nodoc
*/
onChange = (_: any) => {};
/**
* The registered callback function called when a blur event occurs on the input element.
* @nodoc
*/
onTouched = () => {};
constructor(
private _renderer: Renderer2,
private _elementRef: ElementRef,
) {}
/**
* Helper method that sets a property on a target element using the current Renderer
* implementation.
* @nodoc
*/
protected setProperty(key: string, value: any): void {
this._renderer.setProperty(this._elementRef.nativeElement, key, value);
}
/**
* Registers a function called when the control is touched.
* @nodoc
*/
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
/**
* Registers a function called when the control value changes.
* @nodoc
*/
registerOnChange(fn: (_: any) => {}): void {
this.onChange = fn;
}
/**
* Sets the "disabled" property on the range input element.
* @nodoc
*/
setDisabledState(isDisabled: boolean): void {
this.setProperty('disabled', isDisabled);
}
}
/**
* Base class for all built-in ControlValueAccessor classes (except DefaultValueAccessor, which is
* used in case no other CVAs can be found). We use this class to distinguish between default CVA,
* built-in CVAs and custom CVAs, so that Forms logic can recognize built-in CVAs and treat custom
* ones with higher priority (when both built-in and custom CVAs are present).
*
* Note: this is an *internal-only* class and should not be extended or used directly in
* applications code.
*/
@Directive()
export class BuiltInControlValueAccessor extends BaseControlValueAccessor {}
/**
* Used to provide a `ControlValueAccessor` for form controls.
*
* See `DefaultValueAccessor` for how to implement one.
*
* @publicApi
*/
export const NG_VALUE_ACCESSOR = new InjectionToken<ReadonlyArray<ControlValueAccessor>>(
ngDevMode ? 'NgValueAccessor' : '',
);
| {
"end_byte": 6061,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/control_value_accessor.ts"
} |
angular/packages/forms/src/directives/ng_form.ts_0_3946 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AfterViewInit,
computed,
Directive,
EventEmitter,
forwardRef,
Inject,
Input,
Optional,
Provider,
Self,
signal,
untracked,
ɵWritable as Writable,
} from '@angular/core';
import {AbstractControl, FormHooks} from '../model/abstract_model';
import {FormControl} from '../model/form_control';
import {FormGroup} from '../model/form_group';
import {
composeAsyncValidators,
composeValidators,
NG_ASYNC_VALIDATORS,
NG_VALIDATORS,
} from '../validators';
import {ControlContainer} from './control_container';
import {Form} from './form_interface';
import {NgControl} from './ng_control';
import type {NgModel} from './ng_model';
import type {NgModelGroup} from './ng_model_group';
import {
CALL_SET_DISABLED_STATE,
SetDisabledStateOption,
setUpControl,
setUpFormContainer,
syncPendingControls,
} from './shared';
import {AsyncValidator, AsyncValidatorFn, Validator, ValidatorFn} from './validators';
const formDirectiveProvider: Provider = {
provide: ControlContainer,
useExisting: forwardRef(() => NgForm),
};
const resolvedPromise = (() => Promise.resolve())();
/**
* @description
* Creates a top-level `FormGroup` instance and binds it to a form
* to track aggregate form value and validation status.
*
* As soon as you import the `FormsModule`, this directive becomes active by default on
* all `<form>` tags. You don't need to add a special selector.
*
* You optionally export the directive into a local template variable using `ngForm` as the key
* (ex: `#myForm="ngForm"`). This is optional, but useful. Many properties from the underlying
* `FormGroup` instance are duplicated on the directive itself, so a reference to it
* gives you access to the aggregate value and validity status of the form, as well as
* user interaction properties like `dirty` and `touched`.
*
* To register child controls with the form, use `NgModel` with a `name`
* attribute. You may use `NgModelGroup` to create sub-groups within the form.
*
* If necessary, listen to the directive's `ngSubmit` event to be notified when the user has
* triggered a form submission. The `ngSubmit` event emits the original form
* submission event.
*
* In template driven forms, all `<form>` tags are automatically tagged as `NgForm`.
* To import the `FormsModule` but skip its usage in some forms,
* for example, to use native HTML5 validation, add the `ngNoForm` and the `<form>`
* tags won't create an `NgForm` directive. In reactive forms, using `ngNoForm` is
* unnecessary because the `<form>` tags are inert. In that case, you would
* refrain from using the `formGroup` directive.
*
* @usageNotes
*
* ### Listening for form submission
*
* The following example shows how to capture the form values from the "ngSubmit" event.
*
* {@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
*
* ### Setting the update options
*
* The following example shows you how to change the "updateOn" option from its default using
* ngFormOptions.
*
* ```html
* <form [ngFormOptions]="{updateOn: 'blur'}">
* <input name="one" ngModel> <!-- this ngModel will update on blur -->
* </form>
* ```
*
* ### Native DOM validation UI
*
* In order to prevent the native DOM form validation UI from interfering with Angular's form
* validation, Angular automatically adds the `novalidate` attribute on any `<form>` whenever
* `FormModule` or `ReactiveFormModule` are imported into the application.
* If you want to explicitly enable native DOM validation UI with Angular forms, you can add the
* `ngNativeValidate` attribute to the `<form>` element:
*
* ```html
* <form ngNativeValidate>
* ...
* </form>
* ```
*
* @ngModule FormsModule
* @publicApi
*/
| {
"end_byte": 3946,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/ng_form.ts"
} |
angular/packages/forms/src/directives/ng_form.ts_3947_10850 | Directive({
selector: 'form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]',
providers: [formDirectiveProvider],
host: {'(submit)': 'onSubmit($event)', '(reset)': 'onReset()'},
outputs: ['ngSubmit'],
exportAs: 'ngForm',
standalone: false,
})
export class NgForm extends ControlContainer implements Form, AfterViewInit {
/**
* @description
* Returns whether the form submission has been triggered.
*/
get submitted(): boolean {
return untracked(this.submittedReactive);
}
/** @internal */
readonly _submitted = computed(() => this.submittedReactive());
private readonly submittedReactive = signal(false);
private _directives = new Set<NgModel>();
/**
* @description
* The `FormGroup` instance created for this form.
*/
form: FormGroup;
/**
* @description
* Event emitter for the "ngSubmit" event
*/
ngSubmit = new EventEmitter();
/**
* @description
* Tracks options for the `NgForm` instance.
*
* **updateOn**: Sets the default `updateOn` value for all child `NgModels` below it
* unless explicitly set by a child `NgModel` using `ngModelOptions`). Defaults to 'change'.
* Possible values: `'change'` | `'blur'` | `'submit'`.
*
*/
// TODO(issue/24571): remove '!'.
@Input('ngFormOptions') options!: {updateOn?: FormHooks};
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[],
@Optional()
@Self()
@Inject(NG_ASYNC_VALIDATORS)
asyncValidators: (AsyncValidator | AsyncValidatorFn)[],
@Optional()
@Inject(CALL_SET_DISABLED_STATE)
private callSetDisabledState?: SetDisabledStateOption,
) {
super();
this.form = new FormGroup(
{},
composeValidators(validators),
composeAsyncValidators(asyncValidators),
);
}
/** @nodoc */
ngAfterViewInit() {
this._setUpdateStrategy();
}
/**
* @description
* The directive instance.
*/
override get formDirective(): Form {
return this;
}
/**
* @description
* The internal `FormGroup` instance.
*/
override get control(): FormGroup {
return this.form;
}
/**
* @description
* Returns an array representing the path to this group. Because this directive
* always lives at the top level of a form, it is always an empty array.
*/
override get path(): string[] {
return [];
}
/**
* @description
* Returns a map of the controls in this group.
*/
get controls(): {[key: string]: AbstractControl} {
return this.form.controls;
}
/**
* @description
* Method that sets up the control directive in this group, re-calculates its value
* and validity, and adds the instance to the internal list of directives.
*
* @param dir The `NgModel` directive instance.
*/
addControl(dir: NgModel): void {
resolvedPromise.then(() => {
const container = this._findContainer(dir.path);
(dir as Writable<NgModel>).control = <FormControl>(
container.registerControl(dir.name, dir.control)
);
setUpControl(dir.control, dir, this.callSetDisabledState);
dir.control.updateValueAndValidity({emitEvent: false});
this._directives.add(dir);
});
}
/**
* @description
* Retrieves the `FormControl` instance from the provided `NgModel` directive.
*
* @param dir The `NgModel` directive instance.
*/
getControl(dir: NgModel): FormControl {
return <FormControl>this.form.get(dir.path);
}
/**
* @description
* Removes the `NgModel` instance from the internal list of directives
*
* @param dir The `NgModel` directive instance.
*/
removeControl(dir: NgModel): void {
resolvedPromise.then(() => {
const container = this._findContainer(dir.path);
if (container) {
container.removeControl(dir.name);
}
this._directives.delete(dir);
});
}
/**
* @description
* Adds a new `NgModelGroup` directive instance to the form.
*
* @param dir The `NgModelGroup` directive instance.
*/
addFormGroup(dir: NgModelGroup): void {
resolvedPromise.then(() => {
const container = this._findContainer(dir.path);
const group = new FormGroup({});
setUpFormContainer(group, dir);
container.registerControl(dir.name, group);
group.updateValueAndValidity({emitEvent: false});
});
}
/**
* @description
* Removes the `NgModelGroup` directive instance from the form.
*
* @param dir The `NgModelGroup` directive instance.
*/
removeFormGroup(dir: NgModelGroup): void {
resolvedPromise.then(() => {
const container = this._findContainer(dir.path);
if (container) {
container.removeControl(dir.name);
}
});
}
/**
* @description
* Retrieves the `FormGroup` for a provided `NgModelGroup` directive instance
*
* @param dir The `NgModelGroup` directive instance.
*/
getFormGroup(dir: NgModelGroup): FormGroup {
return <FormGroup>this.form.get(dir.path);
}
/**
* Sets the new value for the provided `NgControl` directive.
*
* @param dir The `NgControl` directive instance.
* @param value The new value for the directive's control.
*/
updateModel(dir: NgControl, value: any): void {
resolvedPromise.then(() => {
const ctrl = <FormControl>this.form.get(dir.path!);
ctrl.setValue(value);
});
}
/**
* @description
* Sets the value for this `FormGroup`.
*
* @param value The new value
*/
setValue(value: {[key: string]: any}): void {
this.control.setValue(value);
}
/**
* @description
* Method called when the "submit" event is triggered on the form.
* Triggers the `ngSubmit` emitter to emit the "submit" event as its payload.
*
* @param $event The "submit" event object
*/
onSubmit($event: Event): boolean {
this.submittedReactive.set(true);
syncPendingControls(this.form, this._directives);
this.ngSubmit.emit($event);
// Forms with `method="dialog"` have some special behavior
// that won't reload the page and that shouldn't be prevented.
return ($event?.target as HTMLFormElement | null)?.method === 'dialog';
}
/**
* @description
* Method called when the "reset" event is triggered on the form.
*/
onReset(): void {
this.resetForm();
}
/**
* @description
* Resets the form to an initial value and resets its submitted status.
*
* @param value The new value for the form.
*/
resetForm(value: any = undefined): void {
this.form.reset(value);
this.submittedReactive.set(false);
}
private _setUpdateStrategy() {
if (this.options && this.options.updateOn != null) {
this.form._updateOn = this.options.updateOn;
}
}
private _findContainer(path: string[]): FormGroup {
path.pop();
return path.length ? <FormGroup>this.form.get(path) : this.form;
}
}
| {
"end_byte": 10850,
"start_byte": 3947,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/ng_form.ts"
} |
angular/packages/forms/src/directives/template_driven_errors.ts_0_2310 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵRuntimeError as RuntimeError} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
import {
formControlNameExample,
formGroupNameExample,
ngModelGroupExample,
ngModelWithFormGroupExample,
} from './error_examples';
export function modelParentException(): Error {
return new RuntimeError(
RuntimeErrorCode.NGMODEL_IN_FORM_GROUP,
`
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:
${formControlNameExample}
Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:
Example:
${ngModelWithFormGroupExample}`,
);
}
export function formGroupNameException(): Error {
return new RuntimeError(
RuntimeErrorCode.NGMODEL_IN_FORM_GROUP_NAME,
`
ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.
Option 1: Use formControlName instead of ngModel (reactive strategy):
${formGroupNameExample}
Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):
${ngModelGroupExample}`,
);
}
export function missingNameException(): Error {
return new RuntimeError(
RuntimeErrorCode.NGMODEL_WITHOUT_NAME,
`If ngModel is used within a form tag, either the name attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.
Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">`,
);
}
export function modelGroupParentException(): Error {
return new RuntimeError(
RuntimeErrorCode.NGMODELGROUP_IN_FORM_GROUP,
`
ngModelGroup cannot be used with a parent formGroup directive.
Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):
${formGroupNameExample}
Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):
${ngModelGroupExample}`,
);
}
| {
"end_byte": 2310,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/template_driven_errors.ts"
} |
angular/packages/forms/src/directives/ng_model_group.ts_0_2880 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
forwardRef,
Host,
Inject,
Input,
OnDestroy,
OnInit,
Optional,
Self,
SkipSelf,
} from '@angular/core';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {AbstractFormGroupDirective} from './abstract_form_group_directive';
import {ControlContainer} from './control_container';
import {NgForm} from './ng_form';
import {modelGroupParentException} from './template_driven_errors';
import {AsyncValidator, AsyncValidatorFn, Validator, ValidatorFn} from './validators';
export const modelGroupProvider: any = {
provide: ControlContainer,
useExisting: forwardRef(() => NgModelGroup),
};
/**
* @description
* Creates and binds a `FormGroup` instance to a DOM element.
*
* This directive can only be used as a child of `NgForm` (within `<form>` tags).
*
* Use this directive to validate a sub-group of your form separately from the
* rest of your form, or if some values in your domain model make more sense
* to consume together in a nested object.
*
* Provide a name for the sub-group and it will become the key
* for the sub-group in the form's full value. If you need direct access, export the directive into
* a local template variable using `ngModelGroup` (ex: `#myGroup="ngModelGroup"`).
*
* @usageNotes
*
* ### Consuming controls in a grouping
*
* The following example shows you how to combine controls together in a sub-group
* of the form.
*
* {@example forms/ts/ngModelGroup/ng_model_group_example.ts region='Component'}
*
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector: '[ngModelGroup]',
providers: [modelGroupProvider],
exportAs: 'ngModelGroup',
standalone: false,
})
export class NgModelGroup extends AbstractFormGroupDirective implements OnInit, OnDestroy {
/**
* @description
* Tracks the name of the `NgModelGroup` bound to the directive. The name corresponds
* to a key in the parent `NgForm`.
*/
@Input('ngModelGroup') override name: string = '';
constructor(
@Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[],
@Optional()
@Self()
@Inject(NG_ASYNC_VALIDATORS)
asyncValidators: (AsyncValidator | AsyncValidatorFn)[],
) {
super();
this._parent = parent;
this._setValidators(validators);
this._setAsyncValidators(asyncValidators);
}
/** @internal */
override _checkParentType(): void {
if (
!(this._parent instanceof NgModelGroup) &&
!(this._parent instanceof NgForm) &&
(typeof ngDevMode === 'undefined' || ngDevMode)
) {
throw modelGroupParentException();
}
}
}
| {
"end_byte": 2880,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/ng_model_group.ts"
} |
angular/packages/forms/src/directives/ng_model.ts_0_5808 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
booleanAttribute,
ChangeDetectorRef,
Directive,
EventEmitter,
forwardRef,
Host,
Inject,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
Provider,
Self,
SimpleChanges,
} from '@angular/core';
import {FormHooks} from '../model/abstract_model';
import {FormControl} from '../model/form_control';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {AbstractFormGroupDirective} from './abstract_form_group_directive';
import {ControlContainer} from './control_container';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control';
import {NgForm} from './ng_form';
import {NgModelGroup} from './ng_model_group';
import {
CALL_SET_DISABLED_STATE,
controlPath,
isPropertyUpdated,
selectValueAccessor,
SetDisabledStateOption,
setUpControl,
} from './shared';
import {
formGroupNameException,
missingNameException,
modelParentException,
} from './template_driven_errors';
import {AsyncValidator, AsyncValidatorFn, Validator, ValidatorFn} from './validators';
const formControlBinding: Provider = {
provide: NgControl,
useExisting: forwardRef(() => NgModel),
};
/**
* `ngModel` forces an additional change detection run when its inputs change:
* E.g.:
* ```
* <div>{{myModel.valid}}</div>
* <input [(ngModel)]="myValue" #myModel="ngModel">
* ```
* I.e. `ngModel` can export itself on the element and then be used in the template.
* Normally, this would result in expressions before the `input` that use the exported directive
* to have an old value as they have been
* dirty checked before. As this is a very common case for `ngModel`, we added this second change
* detection run.
*
* Notes:
* - this is just one extra run no matter how many `ngModel`s have been changed.
* - this is a general problem when using `exportAs` for directives!
*/
const resolvedPromise = (() => Promise.resolve())();
/**
* @description
* Creates a `FormControl` instance from a [domain
* model](https://en.wikipedia.org/wiki/Domain_model) and binds it to a form control element.
*
* The `FormControl` instance tracks the value, user interaction, and
* validation status of the control and keeps the view synced with the model. If used
* within a parent form, the directive also registers itself with the form as a child
* control.
*
* This directive is used by itself or as part of a larger form. Use the
* `ngModel` selector to activate it.
*
* It accepts a domain model as an optional `Input`. If you have a one-way binding
* to `ngModel` with `[]` syntax, changing the domain model's value in the component
* class sets the value in the view. If you have a two-way binding with `[()]` syntax
* (also known as 'banana-in-a-box syntax'), the value in the UI always syncs back to
* the domain model in your class.
*
* To inspect the properties of the associated `FormControl` (like the validity state),
* export the directive into a local template variable using `ngModel` as the key (ex:
* `#myVar="ngModel"`). You can then access the control using the directive's `control` property.
* However, the most commonly used properties (like `valid` and `dirty`) also exist on the control
* for direct access. See a full list of properties directly available in
* `AbstractControlDirective`.
*
* @see {@link RadioControlValueAccessor}
* @see {@link SelectControlValueAccessor}
*
* @usageNotes
*
* ### Using ngModel on a standalone control
*
* The following examples show a simple standalone control using `ngModel`:
*
* {@example forms/ts/simpleNgModel/simple_ng_model_example.ts region='Component'}
*
* When using the `ngModel` within `<form>` tags, you'll also need to supply a `name` attribute
* so that the control can be registered with the parent form under that name.
*
* In the context of a parent form, it's often unnecessary to include one-way or two-way binding,
* as the parent form syncs the value for you. You access its properties by exporting it into a
* local template variable using `ngForm` such as (`#f="ngForm"`). Use the variable where
* needed on form submission.
*
* If you do need to populate initial values into your form, using a one-way binding for
* `ngModel` tends to be sufficient as long as you use the exported form's value rather
* than the domain model's value on submit.
*
* ### Using ngModel within a form
*
* The following example shows controls using `ngModel` within a form:
*
* {@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
*
* ### Using a standalone ngModel within a group
*
* The following example shows you how to use a standalone ngModel control
* within a form. This controls the display of the form, but doesn't contain form data.
*
* ```html
* <form>
* <input name="login" ngModel placeholder="Login">
* <input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?
* </form>
* <!-- form value: {login: ''} -->
* ```
*
* ### Setting the ngModel `name` attribute through options
*
* The following example shows you an alternate way to set the name attribute. Here,
* an attribute identified as name is used within a custom form control component. To still be able
* to specify the NgModel's name, you must specify it using the `ngModelOptions` input instead.
*
* ```html
* <form>
* <my-custom-form-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}">
* </my-custom-form-control>
* </form>
* <!-- form value: {user: ''} -->
* ```
*
* @ngModule FormsModule
* @publicApi
*/ | {
"end_byte": 5808,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/ng_model.ts"
} |
angular/packages/forms/src/directives/ng_model.ts_5809_13260 | @Directive({
selector: '[ngModel]:not([formControlName]):not([formControl])',
providers: [formControlBinding],
exportAs: 'ngModel',
standalone: false,
})
export class NgModel extends NgControl implements OnChanges, OnDestroy {
public override readonly control: FormControl = new FormControl();
// At runtime we coerce arbitrary values assigned to the "disabled" input to a "boolean".
// This is not reflected in the type of the property because outside of templates, consumers
// should only deal with booleans. In templates, a string is allowed for convenience and to
// match the native "disabled attribute" semantics which can be observed on input elements.
// This static member tells the compiler that values of type "string" can also be assigned
// to the input in a template.
/** @nodoc */
static ngAcceptInputType_isDisabled: boolean | string;
/** @internal */
_registered = false;
/**
* Internal reference to the view model value.
* @nodoc
*/
viewModel: any;
/**
* @description
* Tracks the name bound to the directive. If a parent form exists, it
* uses this name as a key to retrieve this control's value.
*/
@Input() override name: string = '';
/**
* @description
* Tracks whether the control is disabled.
*/
// TODO(issue/24571): remove '!'.
@Input('disabled') isDisabled!: boolean;
/**
* @description
* Tracks the value bound to this directive.
*/
@Input('ngModel') model: any;
/**
* @description
* Tracks the configuration options for this `ngModel` instance.
*
* **name**: An alternative to setting the name attribute on the form control element. See
* the [example](api/forms/NgModel#using-ngmodel-on-a-standalone-control) for using `NgModel`
* as a standalone control.
*
* **standalone**: When set to true, the `ngModel` will not register itself with its parent form,
* and acts as if it's not in the form. Defaults to false. If no parent form exists, this option
* has no effect.
*
* **updateOn**: Defines the event upon which the form control value and validity update.
* Defaults to 'change'. Possible values: `'change'` | `'blur'` | `'submit'`.
*
*/
// TODO(issue/24571): remove '!'.
@Input('ngModelOptions') options!: {name?: string; standalone?: boolean; updateOn?: FormHooks};
/**
* @description
* Event emitter for producing the `ngModelChange` event after
* the view model updates.
*/
@Output('ngModelChange') update = new EventEmitter();
constructor(
@Optional() @Host() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[],
@Optional()
@Self()
@Inject(NG_ASYNC_VALIDATORS)
asyncValidators: (AsyncValidator | AsyncValidatorFn)[],
@Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
@Optional() @Inject(ChangeDetectorRef) private _changeDetectorRef?: ChangeDetectorRef | null,
@Optional()
@Inject(CALL_SET_DISABLED_STATE)
private callSetDisabledState?: SetDisabledStateOption,
) {
super();
this._parent = parent;
this._setValidators(validators);
this._setAsyncValidators(asyncValidators);
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
/** @nodoc */
ngOnChanges(changes: SimpleChanges) {
this._checkForErrors();
if (!this._registered || 'name' in changes) {
if (this._registered) {
this._checkName();
if (this.formDirective) {
// We can't call `formDirective.removeControl(this)`, because the `name` has already been
// changed. We also can't reset the name temporarily since the logic in `removeControl`
// is inside a promise and it won't run immediately. We work around it by giving it an
// object with the same shape instead.
const oldName = changes['name'].previousValue;
this.formDirective.removeControl({name: oldName, path: this._getPath(oldName)});
}
}
this._setUpControl();
}
if ('isDisabled' in changes) {
this._updateDisabled(changes);
}
if (isPropertyUpdated(changes, this.viewModel)) {
this._updateValue(this.model);
this.viewModel = this.model;
}
}
/** @nodoc */
ngOnDestroy(): void {
this.formDirective && this.formDirective.removeControl(this);
}
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
override get path(): string[] {
return this._getPath(this.name);
}
/**
* @description
* The top-level directive for this control if present, otherwise null.
*/
get formDirective(): any {
return this._parent ? this._parent.formDirective : null;
}
/**
* @description
* Sets the new value for the view model and emits an `ngModelChange` event.
*
* @param newValue The new value emitted by `ngModelChange`.
*/
override viewToModelUpdate(newValue: any): void {
this.viewModel = newValue;
this.update.emit(newValue);
}
private _setUpControl(): void {
this._setUpdateStrategy();
this._isStandalone() ? this._setUpStandalone() : this.formDirective.addControl(this);
this._registered = true;
}
private _setUpdateStrategy(): void {
if (this.options && this.options.updateOn != null) {
this.control._updateOn = this.options.updateOn;
}
}
private _isStandalone(): boolean {
return !this._parent || !!(this.options && this.options.standalone);
}
private _setUpStandalone(): void {
setUpControl(this.control, this, this.callSetDisabledState);
this.control.updateValueAndValidity({emitEvent: false});
}
private _checkForErrors(): void {
if (!this._isStandalone()) {
this._checkParentType();
}
this._checkName();
}
private _checkParentType(): void {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (
!(this._parent instanceof NgModelGroup) &&
this._parent instanceof AbstractFormGroupDirective
) {
throw formGroupNameException();
} else if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) {
throw modelParentException();
}
}
}
private _checkName(): void {
if (this.options && this.options.name) this.name = this.options.name;
if (!this._isStandalone() && !this.name && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw missingNameException();
}
}
private _updateValue(value: any): void {
resolvedPromise.then(() => {
this.control.setValue(value, {emitViewToModelChange: false});
this._changeDetectorRef?.markForCheck();
});
}
private _updateDisabled(changes: SimpleChanges) {
const disabledValue = changes['isDisabled'].currentValue;
// checking for 0 to avoid breaking change
const isDisabled = disabledValue !== 0 && booleanAttribute(disabledValue);
resolvedPromise.then(() => {
if (isDisabled && !this.control.disabled) {
this.control.disable();
} else if (!isDisabled && this.control.disabled) {
this.control.enable();
}
this._changeDetectorRef?.markForCheck();
});
}
private _getPath(controlName: string): string[] {
return this._parent ? controlPath(controlName, this._parent) : [controlName];
}
} | {
"end_byte": 13260,
"start_byte": 5809,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/ng_model.ts"
} |
angular/packages/forms/src/directives/validators.ts_0_8214 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
booleanAttribute,
Directive,
forwardRef,
Input,
OnChanges,
Provider,
SimpleChanges,
} from '@angular/core';
import {Observable} from 'rxjs';
import type {AbstractControl} from '../model/abstract_model';
import {
emailValidator,
maxLengthValidator,
maxValidator,
minLengthValidator,
minValidator,
NG_VALIDATORS,
nullValidator,
patternValidator,
requiredTrueValidator,
requiredValidator,
} from '../validators';
/**
* Method that updates string to integer if not already a number
*
* @param value The value to convert to integer.
* @returns value of parameter converted to number or integer.
*/
function toInteger(value: string | number): number {
return typeof value === 'number' ? value : parseInt(value, 10);
}
/**
* Method that ensures that provided value is a float (and converts it to float if needed).
*
* @param value The value to convert to float.
* @returns value of parameter converted to number or float.
*/
function toFloat(value: string | number): number {
return typeof value === 'number' ? value : parseFloat(value);
}
/**
* @description
* Defines the map of errors returned from failed validation checks.
*
* @publicApi
*/
export type ValidationErrors = {
[key: string]: any;
};
/**
* @description
* An interface implemented by classes that perform synchronous validation.
*
* @usageNotes
*
* ### Provide a custom validator
*
* The following example implements the `Validator` interface to create a
* validator directive with a custom error key.
*
* ```typescript
* @Directive({
* selector: '[customValidator]',
* providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
* })
* class CustomValidatorDirective implements Validator {
* validate(control: AbstractControl): ValidationErrors|null {
* return {'custom': true};
* }
* }
* ```
*
* @publicApi
*/
export interface Validator {
/**
* @description
* Method that performs synchronous validation against the provided control.
*
* @param control The control to validate against.
*
* @returns A map of validation errors if validation fails,
* otherwise null.
*/
validate(control: AbstractControl): ValidationErrors | null;
/**
* @description
* Registers a callback function to call when the validator inputs change.
*
* @param fn The callback function
*/
registerOnValidatorChange?(fn: () => void): void;
}
/**
* A base class for Validator-based Directives. The class contains common logic shared across such
* Directives.
*
* For internal use only, this class is not intended for use outside of the Forms package.
*/
@Directive()
abstract class AbstractValidatorDirective implements Validator, OnChanges {
private _validator: ValidatorFn = nullValidator;
private _onChange!: () => void;
/**
* A flag that tracks whether this validator is enabled.
*
* Marking it `internal` (vs `protected`), so that this flag can be used in host bindings of
* directive classes that extend this base class.
* @internal
*/
_enabled?: boolean;
/**
* Name of an input that matches directive selector attribute (e.g. `minlength` for
* `MinLengthDirective`). An input with a given name might contain configuration information (like
* `minlength='10'`) or a flag that indicates whether validator should be enabled (like
* `[required]='false'`).
*
* @internal
*/
abstract inputName: string;
/**
* Creates an instance of a validator (specific to a directive that extends this base class).
*
* @internal
*/
abstract createValidator(input: unknown): ValidatorFn;
/**
* Performs the necessary input normalization based on a specific logic of a Directive.
* For example, the function might be used to convert string-based representation of the
* `minlength` input to an integer value that can later be used in the `Validators.minLength`
* validator.
*
* @internal
*/
abstract normalizeInput(input: unknown): unknown;
/** @nodoc */
ngOnChanges(changes: SimpleChanges): void {
if (this.inputName in changes) {
const input = this.normalizeInput(changes[this.inputName].currentValue);
this._enabled = this.enabled(input);
this._validator = this._enabled ? this.createValidator(input) : nullValidator;
if (this._onChange) {
this._onChange();
}
}
}
/** @nodoc */
validate(control: AbstractControl): ValidationErrors | null {
return this._validator(control);
}
/** @nodoc */
registerOnValidatorChange(fn: () => void): void {
this._onChange = fn;
}
/**
* @description
* Determines whether this validator should be active or not based on an input.
* Base class implementation checks whether an input is defined (if the value is different from
* `null` and `undefined`). Validator classes that extend this base class can override this
* function with the logic specific to a particular validator directive.
*/
enabled(input: unknown): boolean {
return input != null /* both `null` and `undefined` */;
}
}
/**
* @description
* Provider which adds `MaxValidator` to the `NG_VALIDATORS` multi-provider list.
*/
export const MAX_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MaxValidator),
multi: true,
};
/**
* A directive which installs the {@link MaxValidator} for any `formControlName`,
* `formControl`, or control with `ngModel` that also has a `max` attribute.
*
* @see [Form Validation](guide/forms/form-validation)
*
* @usageNotes
*
* ### Adding a max validator
*
* The following example shows how to add a max validator to an input attached to an
* ngModel binding.
*
* ```html
* <input type="number" ngModel max="4">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'input[type=number][max][formControlName],input[type=number][max][formControl],input[type=number][max][ngModel]',
providers: [MAX_VALIDATOR],
host: {'[attr.max]': '_enabled ? max : null'},
standalone: false,
})
export class MaxValidator extends AbstractValidatorDirective {
/**
* @description
* Tracks changes to the max bound to this directive.
*/
@Input() max!: string | number | null;
/** @internal */
override inputName = 'max';
/** @internal */
override normalizeInput = (input: string | number): number => toFloat(input);
/** @internal */
override createValidator = (max: number): ValidatorFn => maxValidator(max);
}
/**
* @description
* Provider which adds `MinValidator` to the `NG_VALIDATORS` multi-provider list.
*/
export const MIN_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MinValidator),
multi: true,
};
/**
* A directive which installs the {@link MinValidator} for any `formControlName`,
* `formControl`, or control with `ngModel` that also has a `min` attribute.
*
* @see [Form Validation](guide/forms/form-validation)
*
* @usageNotes
*
* ### Adding a min validator
*
* The following example shows how to add a min validator to an input attached to an
* ngModel binding.
*
* ```html
* <input type="number" ngModel min="4">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'input[type=number][min][formControlName],input[type=number][min][formControl],input[type=number][min][ngModel]',
providers: [MIN_VALIDATOR],
host: {'[attr.min]': '_enabled ? min : null'},
standalone: false,
})
export class MinValidator extends AbstractValidatorDirective {
/**
* @description
* Tracks changes to the min bound to this directive.
*/
@Input() min!: string | number | null;
/** @internal */
override inputName = 'min';
/** @internal */
override normalizeInput = (input: string | number): number => toFloat(input);
/** @internal */
override createValidator = (min: number): ValidatorFn => minValidator(min);
} | {
"end_byte": 8214,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/validators.ts"
} |
angular/packages/forms/src/directives/validators.ts_8216_16449 | /**
* @description
* An interface implemented by classes that perform asynchronous validation.
*
* @usageNotes
*
* ### Provide a custom async validator directive
*
* The following example implements the `AsyncValidator` interface to create an
* async validator directive with a custom error key.
*
* ```typescript
* import { of } from 'rxjs';
*
* @Directive({
* selector: '[customAsyncValidator]',
* providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi:
* true}]
* })
* class CustomAsyncValidatorDirective implements AsyncValidator {
* validate(control: AbstractControl): Observable<ValidationErrors|null> {
* return of({'custom': true});
* }
* }
* ```
*
* @publicApi
*/
export interface AsyncValidator extends Validator {
/**
* @description
* Method that performs async validation against the provided control.
*
* @param control The control to validate against.
*
* @returns A promise or observable that resolves a map of validation errors
* if validation fails, otherwise null.
*/
validate(
control: AbstractControl,
): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
/**
* @description
* Provider which adds `RequiredValidator` to the `NG_VALIDATORS` multi-provider list.
*/
export const REQUIRED_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => RequiredValidator),
multi: true,
};
/**
* @description
* Provider which adds `CheckboxRequiredValidator` to the `NG_VALIDATORS` multi-provider list.
*/
export const CHECKBOX_REQUIRED_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => CheckboxRequiredValidator),
multi: true,
};
/**
* @description
* A directive that adds the `required` validator to any controls marked with the
* `required` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
*
* @see [Form Validation](guide/forms/form-validation)
*
* @usageNotes
*
* ### Adding a required validator using template-driven forms
*
* ```
* <input name="fullName" ngModel required>
* ```
*
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
* @publicApi
*/
@Directive({
selector:
':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]',
providers: [REQUIRED_VALIDATOR],
host: {'[attr.required]': '_enabled ? "" : null'},
standalone: false,
})
export class RequiredValidator extends AbstractValidatorDirective {
/**
* @description
* Tracks changes to the required attribute bound to this directive.
*/
@Input() required!: boolean | string;
/** @internal */
override inputName = 'required';
/** @internal */
override normalizeInput = booleanAttribute;
/** @internal */
override createValidator = (input: boolean): ValidatorFn => requiredValidator;
/** @nodoc */
override enabled(input: boolean): boolean {
return input;
}
}
/**
* A Directive that adds the `required` validator to checkbox controls marked with the
* `required` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
*
* @see [Form Validation](guide/forms/form-validation)
*
* @usageNotes
*
* ### Adding a required checkbox validator using template-driven forms
*
* The following example shows how to add a checkbox required validator to an input attached to an
* ngModel binding.
*
* ```
* <input type="checkbox" name="active" ngModel required>
* ```
*
* @publicApi
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
*/
@Directive({
selector:
'input[type=checkbox][required][formControlName],input[type=checkbox][required][formControl],input[type=checkbox][required][ngModel]',
providers: [CHECKBOX_REQUIRED_VALIDATOR],
host: {'[attr.required]': '_enabled ? "" : null'},
standalone: false,
})
export class CheckboxRequiredValidator extends RequiredValidator {
/** @internal */
override createValidator = (input: unknown): ValidatorFn => requiredTrueValidator;
}
/**
* @description
* Provider which adds `EmailValidator` to the `NG_VALIDATORS` multi-provider list.
*/
export const EMAIL_VALIDATOR: any = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => EmailValidator),
multi: true,
};
/**
* A directive that adds the `email` validator to controls marked with the
* `email` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
*
* The email validation is based on the WHATWG HTML specification with some enhancements to
* incorporate more RFC rules. More information can be found on the [Validators.email
* page](api/forms/Validators#email).
*
* @see [Form Validation](guide/forms/form-validation)
*
* @usageNotes
*
* ### Adding an email validator
*
* The following example shows how to add an email validator to an input attached to an ngModel
* binding.
*
* ```
* <input type="email" name="email" ngModel email>
* <input type="email" name="email" ngModel email="true">
* <input type="email" name="email" ngModel [email]="true">
* ```
*
* @publicApi
* @ngModule FormsModule
* @ngModule ReactiveFormsModule
*/
@Directive({
selector: '[email][formControlName],[email][formControl],[email][ngModel]',
providers: [EMAIL_VALIDATOR],
standalone: false,
})
export class EmailValidator extends AbstractValidatorDirective {
/**
* @description
* Tracks changes to the email attribute bound to this directive.
*/
@Input() email!: boolean | string;
/** @internal */
override inputName = 'email';
/** @internal */
override normalizeInput = booleanAttribute;
/** @internal */
override createValidator = (input: number): ValidatorFn => emailValidator;
/** @nodoc */
override enabled(input: boolean): boolean {
return input;
}
}
/**
* @description
* A function that receives a control and synchronously returns a map of
* validation errors if present, otherwise null.
*
* @publicApi
*/
export interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null;
}
/**
* @description
* A function that receives a control and returns a Promise or observable
* that emits validation errors if present, otherwise null.
*
* @publicApi
*/
export interface AsyncValidatorFn {
(
control: AbstractControl,
): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
/**
* @description
* Provider which adds `MinLengthValidator` to the `NG_VALIDATORS` multi-provider list.
*/
export const MIN_LENGTH_VALIDATOR: any = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MinLengthValidator),
multi: true,
};
/**
* A directive that adds minimum length validation to controls marked with the
* `minlength` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
*
* @see [Form Validation](guide/forms/form-validation)
*
* @usageNotes
*
* ### Adding a minimum length validator
*
* The following example shows how to add a minimum length validator to an input attached to an
* ngModel binding.
*
* ```html
* <input name="firstName" ngModel minlength="4">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector: '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]',
providers: [MIN_LENGTH_VALIDATOR],
host: {'[attr.minlength]': '_enabled ? minlength : null'},
standalone: false,
})
export class MinLengthValidator extends AbstractValidatorDirective {
/**
* @description
* Tracks changes to the minimum length bound to this directive.
*/
@Input() minlength!: string | number | null;
/** @internal */
override inputName = 'minlength';
/** @internal */
override normalizeInput = (input: string | number): number => toInteger(input);
/** @internal */
override createValidator = (minlength: number): ValidatorFn => minLengthValidator(minlength);
}
/**
* @description
* Provider which adds `MaxLengthValidator` to the `NG_VALIDATORS` multi-provider list.
*/
export const MAX_LENGTH_VALIDATOR: any = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MaxLengthValidator),
multi: true,
}; | {
"end_byte": 16449,
"start_byte": 8216,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/validators.ts"
} |
angular/packages/forms/src/directives/validators.ts_16451_19354 | /**
* A directive that adds maximum length validation to controls marked with the
* `maxlength` attribute. The directive is provided with the `NG_VALIDATORS` multi-provider list.
*
* @see [Form Validation](guide/forms/form-validation)
*
* @usageNotes
*
* ### Adding a maximum length validator
*
* The following example shows how to add a maximum length validator to an input attached to an
* ngModel binding.
*
* ```html
* <input name="firstName" ngModel maxlength="25">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector: '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]',
providers: [MAX_LENGTH_VALIDATOR],
host: {'[attr.maxlength]': '_enabled ? maxlength : null'},
standalone: false,
})
export class MaxLengthValidator extends AbstractValidatorDirective {
/**
* @description
* Tracks changes to the maximum length bound to this directive.
*/
@Input() maxlength!: string | number | null;
/** @internal */
override inputName = 'maxlength';
/** @internal */
override normalizeInput = (input: string | number): number => toInteger(input);
/** @internal */
override createValidator = (maxlength: number): ValidatorFn => maxLengthValidator(maxlength);
}
/**
* @description
* Provider which adds `PatternValidator` to the `NG_VALIDATORS` multi-provider list.
*/
export const PATTERN_VALIDATOR: any = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => PatternValidator),
multi: true,
};
/**
* @description
* A directive that adds regex pattern validation to controls marked with the
* `pattern` attribute. The regex must match the entire control value.
* The directive is provided with the `NG_VALIDATORS` multi-provider list.
*
* @see [Form Validation](guide/forms/form-validation)
*
* @usageNotes
*
* ### Adding a pattern validator
*
* The following example shows how to add a pattern validator to an input attached to an
* ngModel binding.
*
* ```html
* <input name="firstName" ngModel pattern="[a-zA-Z ]*">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector: '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]',
providers: [PATTERN_VALIDATOR],
host: {'[attr.pattern]': '_enabled ? pattern : null'},
standalone: false,
})
export class PatternValidator extends AbstractValidatorDirective {
/**
* @description
* Tracks changes to the pattern bound to this directive.
*/
@Input()
pattern!: string | RegExp; // This input is always defined, since the name matches selector.
/** @internal */
override inputName = 'pattern';
/** @internal */
override normalizeInput = (input: string | RegExp): string | RegExp => input;
/** @internal */
override createValidator = (input: string | RegExp): ValidatorFn => patternValidator(input);
} | {
"end_byte": 19354,
"start_byte": 16451,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/validators.ts"
} |
angular/packages/forms/src/directives/radio_control_value_accessor.ts_0_7807 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
ElementRef,
forwardRef,
inject,
Injectable,
Injector,
Input,
OnDestroy,
OnInit,
Provider,
Renderer2,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
import {
BuiltInControlValueAccessor,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
} from './control_value_accessor';
import {NgControl} from './ng_control';
import {CALL_SET_DISABLED_STATE, setDisabledStateDefault} from './shared';
const RADIO_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RadioControlValueAccessor),
multi: true,
};
function throwNameError() {
throw new RuntimeError(
RuntimeErrorCode.NAME_AND_FORM_CONTROL_NAME_MUST_MATCH,
`
If you define both a name and a formControlName attribute on your radio button, their values
must match. Ex: <input type="radio" formControlName="food" name="food">
`,
);
}
/**
* @description
* Class used by Angular to track radio buttons. For internal use only.
*/
@Injectable({providedIn: 'root'})
export class RadioControlRegistry {
private _accessors: any[] = [];
/**
* @description
* Adds a control to the internal registry. For internal use only.
*/
add(control: NgControl, accessor: RadioControlValueAccessor) {
this._accessors.push([control, accessor]);
}
/**
* @description
* Removes a control from the internal registry. For internal use only.
*/
remove(accessor: RadioControlValueAccessor) {
for (let i = this._accessors.length - 1; i >= 0; --i) {
if (this._accessors[i][1] === accessor) {
this._accessors.splice(i, 1);
return;
}
}
}
/**
* @description
* Selects a radio button. For internal use only.
*/
select(accessor: RadioControlValueAccessor) {
this._accessors.forEach((c) => {
if (this._isSameGroup(c, accessor) && c[1] !== accessor) {
c[1].fireUncheck(accessor.value);
}
});
}
private _isSameGroup(
controlPair: [NgControl, RadioControlValueAccessor],
accessor: RadioControlValueAccessor,
): boolean {
if (!controlPair[0].control) return false;
return (
controlPair[0]._parent === accessor._control._parent && controlPair[1].name === accessor.name
);
}
}
/**
* @description
* The `ControlValueAccessor` for writing radio control values and listening to radio control
* changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* @usageNotes
*
* ### Using radio buttons with reactive form directives
*
* The follow example shows how to use radio buttons in a reactive form. When using radio buttons in
* a reactive form, radio buttons in the same group should have the same `formControlName`.
* Providing a `name` attribute is optional.
*
* {@example forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts region='Reactive'}
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]',
host: {'(change)': 'onChange()', '(blur)': 'onTouched()'},
providers: [RADIO_VALUE_ACCESSOR],
standalone: false,
})
export class RadioControlValueAccessor
extends BuiltInControlValueAccessor
implements ControlValueAccessor, OnDestroy, OnInit
{
/** @internal */
// TODO(issue/24571): remove '!'.
_state!: boolean;
/** @internal */
// TODO(issue/24571): remove '!'.
_control!: NgControl;
/** @internal */
// TODO(issue/24571): remove '!'.
_fn!: Function;
private setDisabledStateFired = false;
/**
* The registered callback function called when a change event occurs on the input element.
* Note: we declare `onChange` here (also used as host listener) as a function with no arguments
* to override the `onChange` function (which expects 1 argument) in the parent
* `BaseControlValueAccessor` class.
* @nodoc
*/
override onChange = () => {};
/**
* @description
* Tracks the name of the radio input element.
*/
// TODO(issue/24571): remove '!'.
@Input() name!: string;
/**
* @description
* Tracks the name of the `FormControl` bound to the directive. The name corresponds
* to a key in the parent `FormGroup` or `FormArray`.
*/
// TODO(issue/24571): remove '!'.
@Input() formControlName!: string;
/**
* @description
* Tracks the value of the radio input element
*/
@Input() value: any;
private callSetDisabledState =
inject(CALL_SET_DISABLED_STATE, {optional: true}) ?? setDisabledStateDefault;
constructor(
renderer: Renderer2,
elementRef: ElementRef,
private _registry: RadioControlRegistry,
private _injector: Injector,
) {
super(renderer, elementRef);
}
/** @nodoc */
ngOnInit(): void {
this._control = this._injector.get(NgControl);
this._checkName();
this._registry.add(this._control, this);
}
/** @nodoc */
ngOnDestroy(): void {
this._registry.remove(this);
}
/**
* Sets the "checked" property value on the radio input element.
* @nodoc
*/
writeValue(value: any): void {
this._state = value === this.value;
this.setProperty('checked', this._state);
}
/**
* Registers a function called when the control value changes.
* @nodoc
*/
override registerOnChange(fn: (_: any) => {}): void {
this._fn = fn;
this.onChange = () => {
fn(this.value);
this._registry.select(this);
};
}
/** @nodoc */
override setDisabledState(isDisabled: boolean): void {
/**
* `setDisabledState` is supposed to be called whenever the disabled state of a control changes,
* including upon control creation. However, a longstanding bug caused the method to not fire
* when an *enabled* control was attached. This bug was fixed in v15 in #47576.
*
* This had a side effect: previously, it was possible to instantiate a reactive form control
* with `[attr.disabled]=true`, even though the corresponding control was enabled in the
* model. This resulted in a mismatch between the model and the DOM. Now, because
* `setDisabledState` is always called, the value in the DOM will be immediately overwritten
* with the "correct" enabled value.
*
* However, the fix also created an exceptional case: radio buttons. Because Reactive Forms
* models the entire group of radio buttons as a single `FormControl`, there is no way to
* control the disabled state for individual radios, so they can no longer be configured as
* disabled. Thus, we keep the old behavior for radio buttons, so that `[attr.disabled]`
* continues to work. Specifically, we drop the first call to `setDisabledState` if `disabled`
* is `false`, and we are not in legacy mode.
*/
if (
this.setDisabledStateFired ||
isDisabled ||
this.callSetDisabledState === 'whenDisabledForLegacyCode'
) {
this.setProperty('disabled', isDisabled);
}
this.setDisabledStateFired = true;
}
/**
* Sets the "value" on the radio input element and unchecks it.
*
* @param value
*/
fireUncheck(value: any): void {
this.writeValue(value);
}
private _checkName(): void {
if (
this.name &&
this.formControlName &&
this.name !== this.formControlName &&
(typeof ngDevMode === 'undefined' || ngDevMode)
) {
throwNameError();
}
if (!this.name && this.formControlName) this.name = this.formControlName;
}
}
| {
"end_byte": 7807,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/radio_control_value_accessor.ts"
} |
angular/packages/forms/src/directives/checkbox_value_accessor.ts_0_1599 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, forwardRef, Provider} from '@angular/core';
import {
BuiltInControlValueAccessor,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
} from './control_value_accessor';
const CHECKBOX_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxControlValueAccessor),
multi: true,
};
/**
* @description
* A `ControlValueAccessor` for writing a value and listening to changes on a checkbox input
* element.
*
* @usageNotes
*
* ### Using a checkbox with a reactive form.
*
* The following example shows how to use a checkbox with a reactive form.
*
* ```ts
* const rememberLoginControl = new FormControl();
* ```
*
* ```
* <input type="checkbox" [formControl]="rememberLoginControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]',
host: {'(change)': 'onChange($event.target.checked)', '(blur)': 'onTouched()'},
providers: [CHECKBOX_VALUE_ACCESSOR],
standalone: false,
})
export class CheckboxControlValueAccessor
extends BuiltInControlValueAccessor
implements ControlValueAccessor
{
/**
* Sets the "checked" property on the input element.
* @nodoc
*/
writeValue(value: any): void {
this.setProperty('checked', value);
}
}
| {
"end_byte": 1599,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/checkbox_value_accessor.ts"
} |
angular/packages/forms/src/directives/default_value_accessor.ts_0_4144 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵgetDOM as getDOM} from '@angular/common';
import {
Directive,
ElementRef,
forwardRef,
Inject,
InjectionToken,
Optional,
Provider,
Renderer2,
} from '@angular/core';
import {
BaseControlValueAccessor,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
} from './control_value_accessor';
export const DEFAULT_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DefaultValueAccessor),
multi: true,
};
/**
* We must check whether the agent is Android because composition events
* behave differently between iOS and Android.
*/
function _isAndroid(): boolean {
const userAgent = getDOM() ? getDOM().getUserAgent() : '';
return /android (\d+)/.test(userAgent.toLowerCase());
}
/**
* @description
* Provide this token to control if form directives buffer IME input until
* the "compositionend" event occurs.
* @publicApi
*/
export const COMPOSITION_BUFFER_MODE = new InjectionToken<boolean>(
ngDevMode ? 'CompositionEventMode' : '',
);
/**
* The default `ControlValueAccessor` for writing a value and listening to changes on input
* elements. The accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
*
* @usageNotes
*
* ### Using the default value accessor
*
* The following example shows how to use an input element that activates the default value accessor
* (in this case, a text field).
*
* ```ts
* const firstNameControl = new FormControl();
* ```
*
* ```
* <input type="text" [formControl]="firstNameControl">
* ```
*
* This value accessor is used by default for `<input type="text">` and `<textarea>` elements, but
* you could also use it for custom components that have similar behavior and do not require special
* processing. In order to attach the default value accessor to a custom element, add the
* `ngDefaultControl` attribute as shown below.
*
* ```
* <custom-input-component ngDefaultControl [(ngModel)]="value"></custom-input-component>
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
// TODO: vsavkin replace the above selector with the one below it once
// https://github.com/angular/angular/issues/3011 is implemented
// selector: '[ngModel],[formControl],[formControlName]',
host: {
'(input)': '$any(this)._handleInput($event.target.value)',
'(blur)': 'onTouched()',
'(compositionstart)': '$any(this)._compositionStart()',
'(compositionend)': '$any(this)._compositionEnd($event.target.value)',
},
providers: [DEFAULT_VALUE_ACCESSOR],
standalone: false,
})
export class DefaultValueAccessor extends BaseControlValueAccessor implements ControlValueAccessor {
/** Whether the user is creating a composition string (IME events). */
private _composing = false;
constructor(
renderer: Renderer2,
elementRef: ElementRef,
@Optional() @Inject(COMPOSITION_BUFFER_MODE) private _compositionMode: boolean,
) {
super(renderer, elementRef);
if (this._compositionMode == null) {
this._compositionMode = !_isAndroid();
}
}
/**
* Sets the "value" property on the input element.
* @nodoc
*/
writeValue(value: any): void {
const normalizedValue = value == null ? '' : value;
this.setProperty('value', normalizedValue);
}
/** @internal */
_handleInput(value: any): void {
if (!this._compositionMode || (this._compositionMode && !this._composing)) {
this.onChange(value);
}
}
/** @internal */
_compositionStart(): void {
this._composing = true;
}
/** @internal */
_compositionEnd(value: any): void {
this._composing = false;
this._compositionMode && this.onChange(value);
}
}
| {
"end_byte": 4144,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/default_value_accessor.ts"
} |
angular/packages/forms/src/directives/select_control_value_accessor.ts_0_6988 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
ElementRef,
forwardRef,
Host,
Input,
OnDestroy,
Optional,
Provider,
Renderer2,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
import {
BuiltInControlValueAccessor,
ControlValueAccessor,
NG_VALUE_ACCESSOR,
} from './control_value_accessor';
const SELECT_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectControlValueAccessor),
multi: true,
};
function _buildValueString(id: string | null, value: any): string {
if (id == null) return `${value}`;
if (value && typeof value === 'object') value = 'Object';
return `${id}: ${value}`.slice(0, 50);
}
function _extractId(valueString: string): string {
return valueString.split(':')[0];
}
/**
* @description
* The `ControlValueAccessor` for writing select control values and listening to select control
* changes. The value accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* @usageNotes
*
* ### Using select controls in a reactive form
*
* The following examples show how to use a select control in a reactive form.
*
* {@example forms/ts/reactiveSelectControl/reactive_select_control_example.ts region='Component'}
*
* ### Using select controls in a template-driven form
*
* To use a select in a template-driven form, simply add an `ngModel` and a `name`
* attribute to the main `<select>` tag.
*
* {@example forms/ts/selectControl/select_control_example.ts region='Component'}
*
* ### Customizing option selection
*
* Angular uses object identity to select option. It's possible for the identities of items
* to change while the data does not. This can happen, for example, if the items are produced
* from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the
* second response will produce objects with different identities.
*
* To customize the default option comparison algorithm, `<select>` supports `compareWith` input.
* `compareWith` takes a **function** which has two arguments: `option1` and `option2`.
* If `compareWith` is given, Angular selects option by the return value of the function.
*
* ```ts
* const selectedCountriesControl = new FormControl();
* ```
*
* ```
* <select [compareWith]="compareFn" [formControl]="selectedCountriesControl">
* <option *ngFor="let country of countries" [ngValue]="country">
* {{country.name}}
* </option>
* </select>
*
* compareFn(c1: Country, c2: Country): boolean {
* return c1 && c2 ? c1.id === c2.id : c1 === c2;
* }
* ```
*
* **Note:** We listen to the 'change' event because 'input' events aren't fired
* for selects in IE, see:
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event#browser_compatibility
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector:
'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]',
host: {'(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},
providers: [SELECT_VALUE_ACCESSOR],
standalone: false,
})
export class SelectControlValueAccessor
extends BuiltInControlValueAccessor
implements ControlValueAccessor
{
/** @nodoc */
value: any;
/** @internal */
_optionMap: Map<string, any> = new Map<string, any>();
/** @internal */
_idCounter: number = 0;
/**
* @description
* Tracks the option comparison algorithm for tracking identities when
* checking for changes.
*/
@Input()
set compareWith(fn: (o1: any, o2: any) => boolean) {
if (typeof fn !== 'function' && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw new RuntimeError(
RuntimeErrorCode.COMPAREWITH_NOT_A_FN,
`compareWith must be a function, but received ${JSON.stringify(fn)}`,
);
}
this._compareWith = fn;
}
private _compareWith: (o1: any, o2: any) => boolean = Object.is;
/**
* Sets the "value" property on the select element.
* @nodoc
*/
writeValue(value: any): void {
this.value = value;
const id: string | null = this._getOptionId(value);
const valueString = _buildValueString(id, value);
this.setProperty('value', valueString);
}
/**
* Registers a function called when the control value changes.
* @nodoc
*/
override registerOnChange(fn: (value: any) => any): void {
this.onChange = (valueString: string) => {
this.value = this._getOptionValue(valueString);
fn(this.value);
};
}
/** @internal */
_registerOption(): string {
return (this._idCounter++).toString();
}
/** @internal */
_getOptionId(value: any): string | null {
for (const id of this._optionMap.keys()) {
if (this._compareWith(this._optionMap.get(id), value)) return id;
}
return null;
}
/** @internal */
_getOptionValue(valueString: string): any {
const id: string = _extractId(valueString);
return this._optionMap.has(id) ? this._optionMap.get(id) : valueString;
}
}
/**
* @description
* Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* @see {@link SelectControlValueAccessor}
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
@Directive({
selector: 'option',
standalone: false,
})
export class NgSelectOption implements OnDestroy {
/**
* @description
* ID of the option element
*/
// TODO(issue/24571): remove '!'.
id!: string;
constructor(
private _element: ElementRef,
private _renderer: Renderer2,
@Optional() @Host() private _select: SelectControlValueAccessor,
) {
if (this._select) this.id = this._select._registerOption();
}
/**
* @description
* Tracks the value bound to the option element. Unlike the value binding,
* ngValue supports binding to objects.
*/
@Input('ngValue')
set ngValue(value: any) {
if (this._select == null) return;
this._select._optionMap.set(this.id, value);
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
}
/**
* @description
* Tracks simple string values bound to the option element.
* For objects, use the `ngValue` input binding.
*/
@Input('value')
set value(value: any) {
this._setElementValue(value);
if (this._select) this._select.writeValue(this._select.value);
}
/** @internal */
_setElementValue(value: string): void {
this._renderer.setProperty(this._element.nativeElement, 'value', value);
}
/** @nodoc */
ngOnDestroy(): void {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
}
}
| {
"end_byte": 6988,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/select_control_value_accessor.ts"
} |
angular/packages/forms/src/directives/error_examples.ts_0_1471 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export const formControlNameExample = `
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
firstName: new FormControl()
});`;
export const formGroupNameExample = `
<div [formGroup]="myGroup">
<div formGroupName="person">
<input formControlName="firstName">
</div>
</div>
In your class:
this.myGroup = new FormGroup({
person: new FormGroup({ firstName: new FormControl() })
});`;
export const formArrayNameExample = `
<div [formGroup]="myGroup">
<div formArrayName="cities">
<div *ngFor="let city of cityArray.controls; index as i">
<input [formControlName]="i">
</div>
</div>
</div>
In your class:
this.cityArray = new FormArray([new FormControl('SF')]);
this.myGroup = new FormGroup({
cities: this.cityArray
});`;
export const ngModelGroupExample = `
<form>
<div ngModelGroup="person">
<input [(ngModel)]="person.name" name="firstName">
</div>
</form>`;
export const ngModelWithFormGroupExample = `
<div [formGroup]="myGroup">
<input formControlName="firstName">
<input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
</div>
`;
| {
"end_byte": 1471,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/error_examples.ts"
} |
angular/packages/forms/src/directives/reactive_directives/form_group_name.ts_0_7316 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
forwardRef,
Host,
Inject,
Input,
OnDestroy,
OnInit,
Optional,
Provider,
Self,
SkipSelf,
} from '@angular/core';
import {FormArray} from '../../model/form_array';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators';
import {AbstractFormGroupDirective} from '../abstract_form_group_directive';
import {ControlContainer} from '../control_container';
import {arrayParentException, groupParentException} from '../reactive_errors';
import {controlPath} from '../shared';
import {AsyncValidator, AsyncValidatorFn, Validator, ValidatorFn} from '../validators';
import {FormGroupDirective} from './form_group_directive';
const formGroupNameProvider: Provider = {
provide: ControlContainer,
useExisting: forwardRef(() => FormGroupName),
};
/**
* @description
*
* Syncs a nested `FormGroup` or `FormRecord` to a DOM element.
*
* This directive can only be used with a parent `FormGroupDirective`.
*
* It accepts the string name of the nested `FormGroup` or `FormRecord` to link, and
* looks for a `FormGroup` or `FormRecord` registered with that name in the parent
* `FormGroup` instance you passed into `FormGroupDirective`.
*
* Use nested form groups to validate a sub-group of a
* form separately from the rest or to group the values of certain
* controls into their own nested object.
*
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
*
* @usageNotes
*
* ### Access the group by name
*
* The following example uses the `AbstractControl.get` method to access the
* associated `FormGroup`
*
* ```ts
* this.form.get('name');
* ```
*
* ### Access individual controls in the group
*
* The following example uses the `AbstractControl.get` method to access
* individual controls within the group using dot syntax.
*
* ```ts
* this.form.get('name.first');
* ```
*
* ### Register a nested `FormGroup`.
*
* The following example registers a nested *name* `FormGroup` within an existing `FormGroup`,
* and provides methods to retrieve the nested `FormGroup` and individual controls.
*
* {@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'}
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
@Directive({
selector: '[formGroupName]',
providers: [formGroupNameProvider],
standalone: false,
})
export class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy {
/**
* @description
* Tracks the name of the `FormGroup` bound to the directive. The name corresponds
* to a key in the parent `FormGroup` or `FormArray`.
* Accepts a name as a string or a number.
* The name in the form of a string is useful for individual forms,
* while the numerical form allows for form groups to be bound
* to indices when iterating over groups in a `FormArray`.
*/
@Input('formGroupName') override name: string | number | null = null;
constructor(
@Optional() @Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[],
@Optional()
@Self()
@Inject(NG_ASYNC_VALIDATORS)
asyncValidators: (AsyncValidator | AsyncValidatorFn)[],
) {
super();
this._parent = parent;
this._setValidators(validators);
this._setAsyncValidators(asyncValidators);
}
/** @internal */
override _checkParentType(): void {
if (_hasInvalidParent(this._parent) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw groupParentException();
}
}
}
export const formArrayNameProvider: any = {
provide: ControlContainer,
useExisting: forwardRef(() => FormArrayName),
};
/**
* @description
*
* Syncs a nested `FormArray` to a DOM element.
*
* This directive is designed to be used with a parent `FormGroupDirective` (selector:
* `[formGroup]`).
*
* It accepts the string name of the nested `FormArray` you want to link, and
* will look for a `FormArray` registered with that name in the parent
* `FormGroup` instance you passed into `FormGroupDirective`.
*
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
* @see {@link AbstractControl}
*
* @usageNotes
*
* ### Example
*
* {@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'}
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
@Directive({
selector: '[formArrayName]',
providers: [formArrayNameProvider],
standalone: false,
})
export class FormArrayName extends ControlContainer implements OnInit, OnDestroy {
/** @internal */
_parent: ControlContainer;
/**
* @description
* Tracks the name of the `FormArray` bound to the directive. The name corresponds
* to a key in the parent `FormGroup` or `FormArray`.
* Accepts a name as a string or a number.
* The name in the form of a string is useful for individual forms,
* while the numerical form allows for form arrays to be bound
* to indices when iterating over arrays in a `FormArray`.
*/
@Input('formArrayName') override name: string | number | null = null;
constructor(
@Optional() @Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[],
@Optional()
@Self()
@Inject(NG_ASYNC_VALIDATORS)
asyncValidators: (AsyncValidator | AsyncValidatorFn)[],
) {
super();
this._parent = parent;
this._setValidators(validators);
this._setAsyncValidators(asyncValidators);
}
/**
* A lifecycle method called when the directive's inputs are initialized. For internal use only.
* @throws If the directive does not have a valid parent.
* @nodoc
*/
ngOnInit(): void {
this._checkParentType();
this.formDirective!.addFormArray(this);
}
/**
* A lifecycle method called before the directive's instance is destroyed. For internal use only.
* @nodoc
*/
ngOnDestroy(): void {
if (this.formDirective) {
this.formDirective.removeFormArray(this);
}
}
/**
* @description
* The `FormArray` bound to this directive.
*/
override get control(): FormArray {
return this.formDirective!.getFormArray(this);
}
/**
* @description
* The top-level directive for this group if present, otherwise null.
*/
override get formDirective(): FormGroupDirective | null {
return this._parent ? <FormGroupDirective>this._parent.formDirective : null;
}
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
override get path(): string[] {
return controlPath(this.name == null ? this.name : this.name.toString(), this._parent);
}
private _checkParentType(): void {
if (_hasInvalidParent(this._parent) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw arrayParentException();
}
}
}
function _hasInvalidParent(parent: ControlContainer): boolean {
return (
!(parent instanceof FormGroupName) &&
!(parent instanceof FormGroupDirective) &&
!(parent instanceof FormArrayName)
);
}
| {
"end_byte": 7316,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/reactive_directives/form_group_name.ts"
} |
angular/packages/forms/src/directives/reactive_directives/form_control_directive.ts_0_5905 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
EventEmitter,
forwardRef,
Inject,
InjectionToken,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
Provider,
Self,
SimpleChanges,
} from '@angular/core';
import {FormControl} from '../../model/form_control';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '../control_value_accessor';
import {NgControl} from '../ng_control';
import {disabledAttrWarning} from '../reactive_errors';
import {
_ngModelWarning,
CALL_SET_DISABLED_STATE,
cleanUpControl,
isPropertyUpdated,
selectValueAccessor,
SetDisabledStateOption,
setUpControl,
} from '../shared';
import {AsyncValidator, AsyncValidatorFn, Validator, ValidatorFn} from '../validators';
/**
* Token to provide to turn off the ngModel warning on formControl and formControlName.
*/
export const NG_MODEL_WITH_FORM_CONTROL_WARNING = new InjectionToken(
ngDevMode ? 'NgModelWithFormControlWarning' : '',
);
const formControlBinding: Provider = {
provide: NgControl,
useExisting: forwardRef(() => FormControlDirective),
};
/**
* @description
* Synchronizes a standalone `FormControl` instance to a form control element.
*
* Note that support for using the `ngModel` input property and `ngModelChange` event with reactive
* form directives was deprecated in Angular v6 and is scheduled for removal in
* a future version of Angular.
*
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
* @see {@link FormControl}
* @see {@link AbstractControl}
*
* @usageNotes
*
* The following example shows how to register a standalone control and set its value.
*
* {@example forms/ts/simpleFormControl/simple_form_control_example.ts region='Component'}
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
@Directive({
selector: '[formControl]',
providers: [formControlBinding],
exportAs: 'ngForm',
standalone: false,
})
export class FormControlDirective extends NgControl implements OnChanges, OnDestroy {
/**
* Internal reference to the view model value.
* @nodoc
*/
viewModel: any;
/**
* @description
* Tracks the `FormControl` instance bound to the directive.
*/
// TODO(issue/24571): remove '!'.
@Input('formControl') form!: FormControl;
/**
* @description
* Triggers a warning in dev mode that this input should not be used with reactive forms.
*/
@Input('disabled')
set isDisabled(isDisabled: boolean) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
console.warn(disabledAttrWarning);
}
}
// TODO(kara): remove next 4 properties once deprecation period is over
/** @deprecated as of v6 */
@Input('ngModel') model: any;
/** @deprecated as of v6 */
@Output('ngModelChange') update = new EventEmitter();
/**
* @description
* Static property used to track whether any ngModel warnings have been sent across
* all instances of FormControlDirective. Used to support warning config of "once".
*
* @internal
*/
static _ngModelWarningSentOnce = false;
/**
* @description
* Instance property used to track whether an ngModel warning has been sent out for this
* particular `FormControlDirective` instance. Used to support warning config of "always".
*
* @internal
*/
_ngModelWarningSent = false;
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[],
@Optional()
@Self()
@Inject(NG_ASYNC_VALIDATORS)
asyncValidators: (AsyncValidator | AsyncValidatorFn)[],
@Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
@Optional()
@Inject(NG_MODEL_WITH_FORM_CONTROL_WARNING)
private _ngModelWarningConfig: string | null,
@Optional()
@Inject(CALL_SET_DISABLED_STATE)
private callSetDisabledState?: SetDisabledStateOption,
) {
super();
this._setValidators(validators);
this._setAsyncValidators(asyncValidators);
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
/** @nodoc */
ngOnChanges(changes: SimpleChanges): void {
if (this._isControlChanged(changes)) {
const previousForm = changes['form'].previousValue;
if (previousForm) {
cleanUpControl(previousForm, this, /* validateControlPresenceOnChange */ false);
}
setUpControl(this.form, this, this.callSetDisabledState);
this.form.updateValueAndValidity({emitEvent: false});
}
if (isPropertyUpdated(changes, this.viewModel)) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
_ngModelWarning('formControl', FormControlDirective, this, this._ngModelWarningConfig);
}
this.form.setValue(this.model);
this.viewModel = this.model;
}
}
/** @nodoc */
ngOnDestroy() {
if (this.form) {
cleanUpControl(this.form, this, /* validateControlPresenceOnChange */ false);
}
}
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
override get path(): string[] {
return [];
}
/**
* @description
* The `FormControl` bound to this directive.
*/
override get control(): FormControl {
return this.form;
}
/**
* @description
* Sets the new value for the view model and emits an `ngModelChange` event.
*
* @param newValue The new value for the view model.
*/
override viewToModelUpdate(newValue: any): void {
this.viewModel = newValue;
this.update.emit(newValue);
}
private _isControlChanged(changes: {[key: string]: any}): boolean {
return changes.hasOwnProperty('form');
}
}
| {
"end_byte": 5905,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/reactive_directives/form_control_directive.ts"
} |
angular/packages/forms/src/directives/reactive_directives/form_control_name.ts_0_7138 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
EventEmitter,
forwardRef,
Host,
Inject,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
Provider,
Self,
SimpleChanges,
SkipSelf,
ɵWritable as Writable,
} from '@angular/core';
import {FormControl} from '../../model/form_control';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators';
import {AbstractFormGroupDirective} from '../abstract_form_group_directive';
import {ControlContainer} from '../control_container';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '../control_value_accessor';
import {NgControl} from '../ng_control';
import {
controlParentException,
disabledAttrWarning,
ngModelGroupException,
} from '../reactive_errors';
import {_ngModelWarning, controlPath, isPropertyUpdated, selectValueAccessor} from '../shared';
import {AsyncValidator, AsyncValidatorFn, Validator, ValidatorFn} from '../validators';
import {NG_MODEL_WITH_FORM_CONTROL_WARNING} from './form_control_directive';
import {FormGroupDirective} from './form_group_directive';
import {FormArrayName, FormGroupName} from './form_group_name';
const controlNameBinding: Provider = {
provide: NgControl,
useExisting: forwardRef(() => FormControlName),
};
/**
* @description
* Syncs a `FormControl` in an existing `FormGroup` to a form control
* element by name.
*
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
* @see {@link FormControl}
* @see {@link AbstractControl}
*
* @usageNotes
*
* ### Register `FormControl` within a group
*
* The following example shows how to register multiple form controls within a form group
* and set their value.
*
* {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
*
* To see `formControlName` examples with different form control types, see:
*
* * Radio buttons: `RadioControlValueAccessor`
* * Selects: `SelectControlValueAccessor`
*
* ### Use with ngModel is deprecated
*
* Support for using the `ngModel` input property and `ngModelChange` event with reactive
* form directives has been deprecated in Angular v6 and is scheduled for removal in
* a future version of Angular.
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
@Directive({
selector: '[formControlName]',
providers: [controlNameBinding],
standalone: false,
})
export class FormControlName extends NgControl implements OnChanges, OnDestroy {
private _added = false;
/**
* Internal reference to the view model value.
* @internal
*/
viewModel: any;
/**
* @description
* Tracks the `FormControl` instance bound to the directive.
*/
// TODO(issue/24571): remove '!'.
override readonly control!: FormControl;
/**
* @description
* Tracks the name of the `FormControl` bound to the directive. The name corresponds
* to a key in the parent `FormGroup` or `FormArray`.
* Accepts a name as a string or a number.
* The name in the form of a string is useful for individual forms,
* while the numerical form allows for form controls to be bound
* to indices when iterating over controls in a `FormArray`.
*/
@Input('formControlName') override name: string | number | null = null;
/**
* @description
* Triggers a warning in dev mode that this input should not be used with reactive forms.
*/
@Input('disabled')
set isDisabled(isDisabled: boolean) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
console.warn(disabledAttrWarning);
}
}
// TODO(kara): remove next 4 properties once deprecation period is over
/** @deprecated as of v6 */
@Input('ngModel') model: any;
/** @deprecated as of v6 */
@Output('ngModelChange') update = new EventEmitter();
/**
* @description
* Static property used to track whether any ngModel warnings have been sent across
* all instances of FormControlName. Used to support warning config of "once".
*
* @internal
*/
static _ngModelWarningSentOnce = false;
/**
* @description
* Instance property used to track whether an ngModel warning has been sent out for this
* particular FormControlName instance. Used to support warning config of "always".
*
* @internal
*/
_ngModelWarningSent = false;
constructor(
@Optional() @Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[],
@Optional()
@Self()
@Inject(NG_ASYNC_VALIDATORS)
asyncValidators: (AsyncValidator | AsyncValidatorFn)[],
@Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
@Optional()
@Inject(NG_MODEL_WITH_FORM_CONTROL_WARNING)
private _ngModelWarningConfig: string | null,
) {
super();
this._parent = parent;
this._setValidators(validators);
this._setAsyncValidators(asyncValidators);
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
/** @nodoc */
ngOnChanges(changes: SimpleChanges) {
if (!this._added) this._setUpControl();
if (isPropertyUpdated(changes, this.viewModel)) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
_ngModelWarning('formControlName', FormControlName, this, this._ngModelWarningConfig);
}
this.viewModel = this.model;
this.formDirective.updateModel(this, this.model);
}
}
/** @nodoc */
ngOnDestroy(): void {
if (this.formDirective) {
this.formDirective.removeControl(this);
}
}
/**
* @description
* Sets the new value for the view model and emits an `ngModelChange` event.
*
* @param newValue The new value for the view model.
*/
override viewToModelUpdate(newValue: any): void {
this.viewModel = newValue;
this.update.emit(newValue);
}
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
override get path(): string[] {
return controlPath(this.name == null ? this.name : this.name.toString(), this._parent!);
}
/**
* @description
* The top-level directive for this group if present, otherwise null.
*/
get formDirective(): any {
return this._parent ? this._parent.formDirective : null;
}
private _checkParentType(): void {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (
!(this._parent instanceof FormGroupName) &&
this._parent instanceof AbstractFormGroupDirective
) {
throw ngModelGroupException();
} else if (
!(this._parent instanceof FormGroupName) &&
!(this._parent instanceof FormGroupDirective) &&
!(this._parent instanceof FormArrayName)
) {
throw controlParentException(this.name);
}
}
}
private _setUpControl() {
this._checkParentType();
(this as Writable<this>).control = this.formDirective.addControl(this);
this._added = true;
}
}
| {
"end_byte": 7138,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/reactive_directives/form_control_name.ts"
} |
angular/packages/forms/src/directives/reactive_directives/form_group_directive.ts_0_2313 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
computed,
Directive,
EventEmitter,
forwardRef,
Inject,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
Provider,
Self,
signal,
SimpleChanges,
untracked,
ɵWritable as Writable,
} from '@angular/core';
import {FormArray} from '../../model/form_array';
import {FormControl, isFormControl} from '../../model/form_control';
import {FormGroup} from '../../model/form_group';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators';
import {ControlContainer} from '../control_container';
import {Form} from '../form_interface';
import {missingFormException} from '../reactive_errors';
import {
CALL_SET_DISABLED_STATE,
cleanUpControl,
cleanUpFormContainer,
cleanUpValidators,
removeListItem,
SetDisabledStateOption,
setUpControl,
setUpFormContainer,
setUpValidators,
syncPendingControls,
} from '../shared';
import {AsyncValidator, AsyncValidatorFn, Validator, ValidatorFn} from '../validators';
import type {FormControlName} from './form_control_name';
import type {FormArrayName, FormGroupName} from './form_group_name';
import {FormResetEvent, FormSubmittedEvent} from '../../model/abstract_model';
const formDirectiveProvider: Provider = {
provide: ControlContainer,
useExisting: forwardRef(() => FormGroupDirective),
};
/**
* @description
*
* Binds an existing `FormGroup` or `FormRecord` to a DOM element.
*
* This directive accepts an existing `FormGroup` instance. It will then use this
* `FormGroup` instance to match any child `FormControl`, `FormGroup`/`FormRecord`,
* and `FormArray` instances to child `FormControlName`, `FormGroupName`,
* and `FormArrayName` directives.
*
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
* @see {@link AbstractControl}
*
* @usageNotes
* ### Register Form Group
*
* The following example registers a `FormGroup` with first name and last name controls,
* and listens for the *ngSubmit* event when the button is clicked.
*
* {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
*
* @ngModule ReactiveFormsModule
* @publicApi
*/
| {
"end_byte": 2313,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/reactive_directives/form_group_directive.ts"
} |
angular/packages/forms/src/directives/reactive_directives/form_group_directive.ts_2314_10329 | Directive({
selector: '[formGroup]',
providers: [formDirectiveProvider],
host: {'(submit)': 'onSubmit($event)', '(reset)': 'onReset()'},
exportAs: 'ngForm',
standalone: false,
})
export class FormGroupDirective extends ControlContainer implements Form, OnChanges, OnDestroy {
/**
* @description
* Reports whether the form submission has been triggered.
*/
get submitted() {
return untracked(this._submittedReactive);
}
// TODO(atscott): Remove once invalid API usage is cleaned up internally
private set submitted(value: boolean) {
this._submittedReactive.set(value);
}
/** @internal */
readonly _submitted = computed(() => this._submittedReactive());
private readonly _submittedReactive = signal(false);
/**
* Reference to an old form group input value, which is needed to cleanup
* old instance in case it was replaced with a new one.
*/
private _oldForm: FormGroup | undefined;
/**
* Callback that should be invoked when controls in FormGroup or FormArray collection change
* (added or removed). This callback triggers corresponding DOM updates.
*/
private readonly _onCollectionChange = () => this._updateDomValue();
/**
* @description
* Tracks the list of added `FormControlName` instances
*/
directives: FormControlName[] = [];
/**
* @description
* Tracks the `FormGroup` bound to this directive.
*/
@Input('formGroup') form: FormGroup = null!;
/**
* @description
* Emits an event when the form submission has been triggered.
*/
@Output() ngSubmit = new EventEmitter();
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator | ValidatorFn)[],
@Optional()
@Self()
@Inject(NG_ASYNC_VALIDATORS)
asyncValidators: (AsyncValidator | AsyncValidatorFn)[],
@Optional()
@Inject(CALL_SET_DISABLED_STATE)
private callSetDisabledState?: SetDisabledStateOption,
) {
super();
this._setValidators(validators);
this._setAsyncValidators(asyncValidators);
}
/** @nodoc */
ngOnChanges(changes: SimpleChanges): void {
this._checkFormPresent();
if (changes.hasOwnProperty('form')) {
this._updateValidators();
this._updateDomValue();
this._updateRegistrations();
this._oldForm = this.form;
}
}
/** @nodoc */
ngOnDestroy() {
if (this.form) {
cleanUpValidators(this.form, this);
// Currently the `onCollectionChange` callback is rewritten each time the
// `_registerOnCollectionChange` function is invoked. The implication is that cleanup should
// happen *only* when the `onCollectionChange` callback was set by this directive instance.
// Otherwise it might cause overriding a callback of some other directive instances. We should
// consider updating this logic later to make it similar to how `onChange` callbacks are
// handled, see https://github.com/angular/angular/issues/39732 for additional info.
if (this.form._onCollectionChange === this._onCollectionChange) {
this.form._registerOnCollectionChange(() => {});
}
}
}
/**
* @description
* Returns this directive's instance.
*/
override get formDirective(): Form {
return this;
}
/**
* @description
* Returns the `FormGroup` bound to this directive.
*/
override get control(): FormGroup {
return this.form;
}
/**
* @description
* Returns an array representing the path to this group. Because this directive
* always lives at the top level of a form, it always an empty array.
*/
override get path(): string[] {
return [];
}
/**
* @description
* Method that sets up the control directive in this group, re-calculates its value
* and validity, and adds the instance to the internal list of directives.
*
* @param dir The `FormControlName` directive instance.
*/
addControl(dir: FormControlName): FormControl {
const ctrl: any = this.form.get(dir.path);
setUpControl(ctrl, dir, this.callSetDisabledState);
ctrl.updateValueAndValidity({emitEvent: false});
this.directives.push(dir);
return ctrl;
}
/**
* @description
* Retrieves the `FormControl` instance from the provided `FormControlName` directive
*
* @param dir The `FormControlName` directive instance.
*/
getControl(dir: FormControlName): FormControl {
return <FormControl>this.form.get(dir.path);
}
/**
* @description
* Removes the `FormControlName` instance from the internal list of directives
*
* @param dir The `FormControlName` directive instance.
*/
removeControl(dir: FormControlName): void {
cleanUpControl(dir.control || null, dir, /* validateControlPresenceOnChange */ false);
removeListItem(this.directives, dir);
}
/**
* Adds a new `FormGroupName` directive instance to the form.
*
* @param dir The `FormGroupName` directive instance.
*/
addFormGroup(dir: FormGroupName): void {
this._setUpFormContainer(dir);
}
/**
* Performs the necessary cleanup when a `FormGroupName` directive instance is removed from the
* view.
*
* @param dir The `FormGroupName` directive instance.
*/
removeFormGroup(dir: FormGroupName): void {
this._cleanUpFormContainer(dir);
}
/**
* @description
* Retrieves the `FormGroup` for a provided `FormGroupName` directive instance
*
* @param dir The `FormGroupName` directive instance.
*/
getFormGroup(dir: FormGroupName): FormGroup {
return <FormGroup>this.form.get(dir.path);
}
/**
* Performs the necessary setup when a `FormArrayName` directive instance is added to the view.
*
* @param dir The `FormArrayName` directive instance.
*/
addFormArray(dir: FormArrayName): void {
this._setUpFormContainer(dir);
}
/**
* Performs the necessary cleanup when a `FormArrayName` directive instance is removed from the
* view.
*
* @param dir The `FormArrayName` directive instance.
*/
removeFormArray(dir: FormArrayName): void {
this._cleanUpFormContainer(dir);
}
/**
* @description
* Retrieves the `FormArray` for a provided `FormArrayName` directive instance.
*
* @param dir The `FormArrayName` directive instance.
*/
getFormArray(dir: FormArrayName): FormArray {
return <FormArray>this.form.get(dir.path);
}
/**
* Sets the new value for the provided `FormControlName` directive.
*
* @param dir The `FormControlName` directive instance.
* @param value The new value for the directive's control.
*/
updateModel(dir: FormControlName, value: any): void {
const ctrl = <FormControl>this.form.get(dir.path);
ctrl.setValue(value);
}
/**
* @description
* Method called with the "submit" event is triggered on the form.
* Triggers the `ngSubmit` emitter to emit the "submit" event as its payload.
*
* @param $event The "submit" event object
*/
onSubmit($event: Event): boolean {
this._submittedReactive.set(true);
syncPendingControls(this.form, this.directives);
this.ngSubmit.emit($event);
this.form._events.next(new FormSubmittedEvent(this.control));
// Forms with `method="dialog"` have some special behavior that won't reload the page and that
// shouldn't be prevented. Note that we need to null check the `event` and the `target`, because
// some internal apps call this method directly with the wrong arguments.
return ($event?.target as HTMLFormElement | null)?.method === 'dialog';
}
/**
* @description
* Method called when the "reset" event is triggered on the form.
*/
onReset(): void {
this.resetForm();
}
/**
* @description
* Resets the form to an initial value and resets its submitted status.
*
* @param value The new value for the form.
*/
resetForm(value: any = undefined): void {
this.form.reset(value);
this._submittedReactive.set(false);
this.form._events.next(new FormResetEvent(this.form));
}
/** @internal */
| {
"end_byte": 10329,
"start_byte": 2314,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/reactive_directives/form_group_directive.ts"
} |
angular/packages/forms/src/directives/reactive_directives/form_group_directive.ts_10332_12932 | updateDomValue() {
this.directives.forEach((dir) => {
const oldCtrl = dir.control;
const newCtrl = this.form.get(dir.path);
if (oldCtrl !== newCtrl) {
// Note: the value of the `dir.control` may not be defined, for example when it's a first
// `FormControl` that is added to a `FormGroup` instance (via `addControl` call).
cleanUpControl(oldCtrl || null, dir);
// Check whether new control at the same location inside the corresponding `FormGroup` is an
// instance of `FormControl` and perform control setup only if that's the case.
// Note: we don't need to clear the list of directives (`this.directives`) here, it would be
// taken care of in the `removeControl` method invoked when corresponding `formControlName`
// directive instance is being removed (invoked from `FormControlName.ngOnDestroy`).
if (isFormControl(newCtrl)) {
setUpControl(newCtrl, dir, this.callSetDisabledState);
(dir as Writable<FormControlName>).control = newCtrl;
}
}
});
this.form._updateTreeValidity({emitEvent: false});
}
private _setUpFormContainer(dir: FormArrayName | FormGroupName): void {
const ctrl: any = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
// NOTE: this operation looks unnecessary in case no new validators were added in
// `setUpFormContainer` call. Consider updating this code to match the logic in
// `_cleanUpFormContainer` function.
ctrl.updateValueAndValidity({emitEvent: false});
}
private _cleanUpFormContainer(dir: FormArrayName | FormGroupName): void {
if (this.form) {
const ctrl: any = this.form.get(dir.path);
if (ctrl) {
const isControlUpdated = cleanUpFormContainer(ctrl, dir);
if (isControlUpdated) {
// Run validity check only in case a control was updated (i.e. view validators were
// removed) as removing view validators might cause validity to change.
ctrl.updateValueAndValidity({emitEvent: false});
}
}
}
}
private _updateRegistrations() {
this.form._registerOnCollectionChange(this._onCollectionChange);
if (this._oldForm) {
this._oldForm._registerOnCollectionChange(() => {});
}
}
private _updateValidators() {
setUpValidators(this.form, this);
if (this._oldForm) {
cleanUpValidators(this._oldForm, this);
}
}
private _checkFormPresent() {
if (!this.form && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw missingFormException();
}
}
}
| {
"end_byte": 12932,
"start_byte": 10332,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/directives/reactive_directives/form_group_directive.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.