How to use @angular/forms - 10 common examples

To help you get started, we’ve selected a few @angular/forms examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DBCG / Dataphor / Dataphor / Frontend.Client.Angular / dataphor-frontend-client / src / app / d4 / frontend / source / source.component.ts View on Github external
ngOnInit() {
        this.formGroup = this._form.addSource(this.name, new FormGroup({}));

        let decodedSource = this._utilityService.decodeInline(this.expression);

        let decodedQuery = 'select ' + decodedSource;
        this._apiService
            .post({ value: decodedQuery })
            .then(response => {
                //let handledResponse = this._apiService.handleResponse(response);
                console.log(response);
                if (Array.isArray(response)) {
                    // Return first value from array of objects
                    this._form.updateGroup(this.name, this.formGroup, this._utilityService.getValueFromSourceValue(response[0]));
                }
                else {
                    this._form.updateGroup(this.name, this.formGroup, this._utilityService.getValueFromSourceValue(response));
                }
github spderosso / deja-vu / packages / catalog / market / src / app / market / create-good-name / create-good-name.component.ts View on Github external
{
      provide: NG_VALIDATORS,
      useExisting: CreateGoodNameComponent,
      multi: true
    }
  ]
})
export class CreateGoodNameComponent
    implements OnInit, ControlValueAccessor, Validator {
  @Input() initialValue: string;
  @Output() name: EventEmitter = new EventEmitter();

  // Presentation input
  @Input() inputLabel: string = 'Name';

  nameControl = new FormControl(this.initialValue, [Validators.required]);

  constructor(private elem: ElementRef, private rs: RunService) {}

  ngOnInit() {
    this.nameControl.valueChanges.subscribe((newValue: string) => {
      this.name.emit(newValue);
    });
    this.nameControl.valueChanges.pipe(startWith(this.nameControl.value));
    // set initial value after subscribing to changes so that it will be emitted
    this.nameControl.setValue(this.initialValue);
  }

  writeValue(value: any) {
    if (value) {
      this.nameControl.setValue(value);
    } else {
github bfwg / angular-spring-starter / frontend / src / app / signup / signup.component.ts View on Github external
ngOnInit() {
    this.route.params
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe((params: DisplayMessage) => {
        this.notification = params;
      });
    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    this.form = this.formBuilder.group({
      username: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(64)])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(32)])],
      firstname: [''],
      lastname: ['']
    });
  }
github yuyang041060120 / ng2-validation / src / custom-validators.ts View on Github external
static creditCard(control: AbstractControl): {[key: string]: boolean} {
    if (isPresent(Validators.required(control))) return null;

    let v: string = control.value;

    let sanitized = v.replace(/[^0-9]+/g, '');

    // problem with chrome
    if (!(/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/.test(sanitized))) {
      return {'creditCard': true};
    }

    let sum = 0;
    let digit;
    let tmpNum;
    let shouldDouble;
    for (let i = sanitized.length - 1; i >= 0; i--) {
      digit = sanitized.substring(i, (i + 1));
github bwsw / cloudstack-ui / src / app / shared / directives / forbidden-values.directive.ts View on Github external
import { Directive, Input, OnInit } from '@angular/core';
import { FormControl, NG_VALIDATORS, Validator, Validators } from '@angular/forms';
import { forbiddenValuesValidator } from './forbidden-values-validator';

@Directive({
  // tslint:disable-next-line
  selector: '[forbiddenValues]',
  providers: [{ provide: NG_VALIDATORS, useExisting: ForbiddenValuesDirective, multi: true }],
})
export class ForbiddenValuesDirective implements OnInit, Validator {
  @Input()
  public forbiddenValues: string[];
  private validator = Validators.nullValidator;

  public ngOnInit(): void {
    this.validator = forbiddenValuesValidator(this.forbiddenValues);
  }

  public validate(c: FormControl): { [key: string]: any } {
    return this.validator(c);
  }
}
github eosrio / simpleos / src / app / dynamic-form-builder / dynamic-form-builder.component.js View on Github external
DynamicFormBuilderComponent.prototype.ngOnInit = function () {
        var fieldsCtrls = {};
        for (var _i = 0, _a = this.fields; _i < _a.length; _i++) {
            var f = _a[_i];
            // console.log(f);
            if (f.type === 'text') {
                if (f.typeDef === 'name' || f.typeDef === 'account_name') {
                    var unamePattern = '^([a-z]|[1-5])+$';
                    fieldsCtrls[f.name] = new forms_1.FormControl(f.value || '', [forms_1.Validators.pattern(unamePattern), forms_1.Validators.maxLength(12)]);
                }
                else {
                    fieldsCtrls[f.name] = new forms_1.FormControl(f.value || '');
                }
            }
            else {
                var opts = {};
                console.log(f.options);
                for (var _b = 0, _c = f.options; _b < _c.length; _b++) {
                    var opt = _c[_b];
                    opts[opt.key] = new forms_1.FormControl(opt.value);
                }
                fieldsCtrls[f.name] = new forms_1.FormGroup(opts);
            }
        }
        this.form = new forms_1.FormGroup(fieldsCtrls);
github Azure / BatchExplorer / src / app / components / gallery / submit / submit-ncj-template.component.ts View on Github external
if (template.parameters[key].defaultValue === "") {
                    validator = null;
                }
            }

            templateFormGroup[key] = new FormControl(defaultValue, validator);
            if (template.parameters[key].metadata && template.parameters[key].metadata.advancedType) {
                // Store the advanced data type as we need it for change events from file-groups
                this._parameterTypeMap[key] = template.parameters[key].metadata.advancedType;
            }

            // Wire up a control change event handler
            this._handleControlChangeEvents(templateFormGroup, key);
        }

        return new FormGroup(templateFormGroup);
    }
github AngularTemplates / angular-forms-and-validations / src / app / forms / forms.component.ts View on Github external
createForms() {
    // matching passwords validation
    this.matching_passwords_group = new FormGroup({
      password: new FormControl('', Validators.compose([
        Validators.minLength(5),
        Validators.required,
        Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$')
      ])),
      confirm_password: new FormControl('', Validators.required)
    }, (formGroup: FormGroup) => {
      return PasswordValidator.areEqual(formGroup);
    });

    // country & phone validation
    let country = new FormControl(this.countries[0], Validators.required);

    let phone = new FormControl('', {
      validators: Validators.compose([
        Validators.required,
        PhoneValidator.validCountryPhone(country)
      ])
    });
github heloufir / ngx-security-starter / front-end / src / app / main / account-settings / account-settings.component.ts View on Github external
this.loadingProfiles = true;
    this.profileService.find()
      .subscribe((res: PartialList) => {
        this.profiles = res.data;
        this.loadingProfiles = false;
      });
    if (!this.selectedUser.picture) {
      this.picturePreview = 'assets/images/faces/avatar.png';
    } else {
      this.picturePreview = environment.web_url + 'users/picture/' + this.selectedUser.id + '?v=' + Math.random();
    }
    // Initialize the form group object
    this.form = this._fb.group({
      email: [
        this.selectedUser ? this.selectedUser.email : '',
        [Validators.required, Validators.maxLength(255)]
      ],
      name: [
        this.selectedUser ? this.selectedUser.name : '',
        [Validators.required, Validators.maxLength(255)]
      ],
      password: [
        '',
        this.selectedUser && this.selectedUser.id ? [] : [Validators.required]
      ],
      password_confirmation: [
        '',
        this.selectedUser && this.selectedUser.id ? [] : [Validators.required]
      ]
    });
  }
github Teradata / covalent / src / platform / dynamic-forms / services / dynamic-forms.service.ts View on Github external
createValidators(config: ITdDynamicElementConfig): ValidatorFn {
    let validator: ValidatorFn;
    if (config.required) {
      validator = Validators.required;
    }
    if (config.max || config.max === 0) {
      validator = Validators.compose([validator, Validators.max(parseFloat(config.max))]);
    }
    if (config.min || config.min === 0) {
      validator = Validators.compose([validator, Validators.min(parseFloat(config.min))]);
    }
    if (config.maxLength || config.maxLength === 0) {
      validator = Validators.compose([validator, Validators.maxLength(parseFloat(config.maxLength))]);
    }
    if (config.minLength || config.minLength === 0) {
      validator = Validators.compose([validator, Validators.minLength(parseFloat(config.minLength))]);
    }
    // Add provided custom validators to the validator function
    if (config.validators) {
      config.validators.forEach((validatorConfig: ITdDynamicElementValidator) => {
        validator = Validators.compose([validator, validatorConfig.validator]);
      });
    }
    return validator;
  }
}