what is formgroup in angular code example

Example 1: angular add formgroup to formgroup

this.myForm = this.fb.group({
  name: ['', [Validators.required]],
  contacts: this.fb.group({
    email: ['', [Validators.email]],
  })
});

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<mat-grid-list cols="2" rowHeight="85px">
<!-- name -->
<mat-grid-tile>
  <mat-form-field>
    <input matInput type="text" formControlName="name">
    <mat-error *ngIf="form.controls.name.hasError('required')">Name required</mat-error>
  </mat-form-field>
</mat-grid-tile>   
<!-- contacts -->
<div formGroupName="contacts">
	<!-- email -->
	<mat-grid-tile>
  		<mat-form-field>
    		<input matInput type="text" formControlName="email">
	    	<mat-error *ngIf="form.get('contacts').get('email').hasError('required')">Email required</mat-error>
		</mat-form-field>
	</mat-grid-tile>
</div>
</form>
</mat-grid-list>

Example 2: formgroup angular

content_copy
      
      const form = new FormGroup({
  first: new FormControl('Nancy', Validators.minLength(2)),
  last: new FormControl('Drew'),
});

console.log(form.value);   // {first: 'Nancy', last; 'Drew'}
console.log(form.status);  // 'VALID'

Example 3: get formcontrol value

this.loginForm = new FormGroup({
  'email': new FormControl('', { validators: [Validators.required] })
});
// get like this
const { email } = this.loginForm.value;

Example 4: formbuilder angular example

this.contactForm = this.formBuilder.group({
  firstname: ['', [Validators.required, Validators.minLength(10)]],
  lastname: ['', [Validators.required, Validators.maxLength(15), Validators.pattern("^[a-zA-Z]+$")]],
  email: ['', [Validators.required, Validators.email]],
  gender: ['', [Validators.required]],
  isMarried: ['', [Validators.required]],
  country: ['', [Validators.required]],
  address: this.formBuilder.group({
    city: ['', [Validators.required]],
    street: ['', [Validators.required]],
    pincode: ['', [Validators.required]],
  })
});

Tags:

Html Example