Skip to content

Instantly share code, notes, and snippets.

@Teebo
Created January 31, 2021 12:01
Show Gist options
  • Save Teebo/16cd6039faa20b50556d36fa84d1fabd to your computer and use it in GitHub Desktop.
Save Teebo/16cd6039faa20b50556d36fa84d1fabd to your computer and use it in GitHub Desktop.
HeroComponent - Parent form
<form [formGroup]="heroForm">
<nb-card>
<nb-card-header>Hero</nb-card-header>
<nb-card-body class="col">
<input
formControlName="heroName"
type="text"
nbInput
placeholder="Hero name"
/>
<input formControlName="aka" type="text" nbInput placeholder="AKA" />
</nb-card-body>
</nb-card>
<nb-card>
<nb-card-header>Super Power</nb-card-header>
<nb-card-body class="col">
<app-powers></app-powers>
</nb-card-body>
</nb-card>
<nb-card>
<nb-card-header>Hobbies</nb-card-header>
<nb-card-body class="col">
<app-hobbies
[parentForm]="heroForm"
[formGroup]="heroForm.get('hobbies')"
></app-hobbies>
</nb-card-body>
</nb-card>
<button (click)="logFormData()" nbButton status="primary">Submit</button>
</form>
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PowersComponent } from '../powers/powers.component';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.scss']
})
export class HeroComponent implements OnInit {
@ViewChild(PowersComponent, { static: true }) public powersComponent: PowersComponent;
public heroForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
}
public ngOnInit(): void {
this.heroForm = this.formBuilder.group({
heroName: ['', Validators.required],
aka: ['', Validators.required],
powers: this.powersComponent.createFormGroup(),
hobbies: this.formBuilder.group({
favoriteHobby: ['', Validators.required]
})
})
}
public logFormData(): void {
console.log(this.heroForm.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment