Skip to content

Instantly share code, notes, and snippets.

@sharbel93
Created May 15, 2020 12:03
Show Gist options
  • Save sharbel93/2cc9fa694c7050c0e992eacbbb510a3d to your computer and use it in GitHub Desktop.
Save sharbel93/2cc9fa694c7050c0e992eacbbb510a3d to your computer and use it in GitHub Desktop.
// component.ts
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { QuestionBase } from './question-base';
import { QuestionControlService } from './question-control.service';
@Component({
selector: 'app-dynamic-form',
templateUrl: './dynamic-form.component.html',
providers: [ QuestionControlService ]
})
export class DynamicFormComponent implements OnInit {
@Input() questions: QuestionBase<string>[] = [];
form: FormGroup;
payLoad = '';
// name_one = new FormControl('');
// name_two = new FormControl('');
profileForm = this.fb.group({
name_one: ['', Validators.required],
name_two: ['', Validators.required],
});
constructor(private qcs: QuestionControlService, private fb: FormBuilder) { }
ngOnInit() {
this.form = this.qcs.toFormGroup(this.questions);
}
onSubmit() {
console.log('parent values', this.profileForm.value);
console.log('child values', this.form.value);
const child = this.profileForm.value
const parent = this.form.value
console.log(Object.assign(parent, child));
this.payLoad = JSON.stringify(this.form.getRawValue());
}
}
// HTML
<div>
<form (ngSubmit)="onSubmit()" [formGroup]="profileForm">
<div *ngFor="let question of questions" class="form-row" style="margin: 2rem 0">
<app-question [question]="question" [form]="form"></app-question>
</div>
<input type="text" formControlName="name_one">
<input type="text" formControlName="name_two">
<div class="form-row">
<button type="submit" [disabled]="!form.valid">Save</button>
</div>
</form>
Value: {{ name_one.value }}
Value2: {{ name_two.value }}
<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
</div>
<!--
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 http://angular.io/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 http://angular.io/license
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment