Reputation: 1
Hi everyone i am doing a "dinamic" form with Angular and i am having some problems to get the values that input in form, my code is:
HTML
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" *ngFor="let con of controls" novalidate>
<div class="form-group" *ngIf = "con.type != 'submit'">
<label for="{{con.id}}">{{con.label}}</label>
<input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}">
</div>
<input *ngIf = "con.type == 'submit'" type="submit" class="{{con.class}}" value={{con.label}}>
</form>
Component:
import { Component ,Input} from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'form-tag',
templateUrl: './form.html',
})
export class FormComponent {
@Input() controls: any[];
onSubmit(sub: NgForm)
{
console.log(sub.email);
}
}
the problem is that when i submit the form console.log(sub.email); return an empty object
Upvotes: 0
Views: 2041
Reputation: 4353
I'm not really really sure what you're trying to do but it seems like you're looping over controls with the <form>
tag instead of just with the div.form-group
and the <input />
itself.
Maybe wrap those in an <ng-template />
and loop through it and not the <form>
tag?
So something like this:
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" novalidate>
<ng-template *ngFor="let con of controls">
<div class="form-group" *ngIf="con.type != 'submit'">
<label for="{{con.id}}">{{con.label}}</label>
<input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}" />
</div>
<input *ngIf="con.type == 'submit'" type="submit" class="{{con.class}}" [value]="con.label" />
</form>
Upvotes: 0
Reputation: 12376
Since you use ngForm, it's a template driven form and not a reactive one. In template driven forms you need to pass myForm.value to onSubmit():
onSubmit(myForm.value)
Also, from your code sample, it's not clear what's con.
Upvotes: 1