Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
- import { AbstractControl, FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
- @Component({
- selector: 'app-root',
- template: `
- <form [formGroup]="form" (ngSubmit)="save()">
- <input type="text" formControlName="username" class="form-control" placeholder="user name">
- <div formGroupName="passwords">
- <input type="text" formControlName="password1">
- <input type="text" formControlName="password2">
- </div>
- 1: {{form.get('passwords').get('password1').errors | json }}
- <br>
- 2: {{form.get('passwords').get('password2').errors | json }}
- <button [disabled]="form.invalid">save</button>
- </form>
- `,
- })
- export class AppComponent {
- form: FormGroup;
- step = 0;
- constructor(private fb: FormBuilder) {
- this.form = fb.group({
- username: ['', Validators.required],
- passwords: fb.group(
- {
- password1: ['', [ Validators.required, Validators.minLength(3)]],
- password2: ['', [ Validators.required, Validators.minLength(3)]],
- },
- {
- validator: passwordMatch()
- }
- )
- });
- }
- save(): void {
- console.log(this.form.value)
- }
- }
- function passwordMatch(): any {
- return (group: FormGroup) => {
- const pass1 = group.get('password1');
- const pass2 = group.get('password2');
- if (!pass2.errors && pass1.value === pass2.value) {
- pass2.setErrors(null)
- } else {
- pass2.setErrors({ ...pass2.errors, noMatch: true })
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement