how to get json object from genereted textfield using angular 2 - javascript

I'm trying to add textfield dynamically with angular 2 and it works as expected,but couldn't managed to get this json object :
exemple of json object which i want to get when i clic the submit button :
{fullname:"toto",etapes:[{etape:"sometext"},{etape:"sometext"}]}
heres the HTML CODE:
<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)">
<div style="padding:15px" class="container" style="width: 1027px !important;">
<div class="itineraire">
<div class="panel panel-default" style="width:100%">
<div class="panel-heading panelcolor"><span style="font-size: 15px;font-weight: bold">Itinéraire</span></div>
<div class="panel-body panelcolor">
<input type="text" formControlName="fullname" class="form-control" placeholder="fullename"
name="Location" >
<div formArrayName="myArray">
<div *ngFor="let myGroup of myForm.controls.myArray.controls; let i=index">
<div [formGroupName]="i">
<span *ngIf="myForm.controls.myArray.controls.length > 1" (click)="removeDataKey(i)" class="glyphicon glyphicon-remove pull-right"
style="z-index:33;cursor: pointer">
</span>
<!--[formGroupName]="myGroupName[i]"-->
<div [formGroupName]="myGroupName[i]">
<div class="inner-addon left-addon ">
<i class="glyphicon marker" style="border: 5px solid #FED141"></i>
<input type="text" style="width:50% !important" formControlName="etape" class="form-control" placeholder="Exemple : Maarif, Grand Casablanca"
name="Location" (setAddress)="getAddressOnChange($event,LocationCtrl)"><br/>
</div>
</div>
<!--[formGroupName]="myGroupName[i]"-->
</div>
<!--[formGroupName]="i" -->
</div>
</div>
<br/>
<a (click)="addArray()" style="cursor: pointer">+ Ajouter une ville étape</a>
<input type="text" style="width:30%" #newName id="newName" [hidden]="true">
</div>
</div>
<button type="submit" (click)="save()">save</button>
</form>
Component.ts :
initArray(nameObj:any) {
return this._fb.group({
[nameObj]: this._fb.group({
etape: [''],
gmtDate:[''],
})
});
}
addArray(newName:string) {
const control = <FormArray>this.myForm.controls['myArray'];
this.myGroupName.push(newName);
control.push(this.initArray(newName));
}
ngOnInit() {
this.myForm = this._fb.group({
myArray: this._fb.array([
this._fb.group({
test: this._fb.group({
etape: [''],
gmtDate:['']
})
}),
])
});
}
save(){
console.log(myObject);
}
so, what are the changes that i have to do in my code to get the like the Json object above, when i click the submit button, please help i got stuck on this.

If you want:
{fullname:"toto",etapes:[{etape:"sometext"},{etape:"sometext"}]}
your form should looks like: (we dont need the formGroupName )
this.myForm = this._fb.group({
fullname: ['', Validators.required ],
etapes: this._fb.array([
this._fb.group({
etape: ['']
},
this._fb.group({
etape: ['']
},
...
)
])
});
So, to have it dynamically, your initArray()should be like:
initArray() {
return this._fb.group({
etape: ['']
});
}
and adding an array should looks like:
addArray(newName:string) {
const control = <FormArray>this.myForm.controls['etapes']
control.push(this.initArray());
}
NB: You dont need the (click)="save()" anymore in the submit button, since you already call it when submit.
a working plunker: http://plnkr.co/edit/Nq4jrC5g0tfxE0NCTfoQ?p=preview

HI can you try like this
save(){
console.log(this.myForm.value);
}

#imsi imsi
you have
<div [formGroupName]="myGroupName[i]"> //WRONG
<div [formGroupName]="myGroup[i]"> //<--it's myGroup

Related

set value in form array in angular 8

i have a edit form in angular 8 and use the form array in that .
i need when i enter that page it fill the form array with value but when i enter the page it not fill the form .
whats the problem ???
ngOnInit(): void {
this.courseExam = this.activeRoute.snapshot.data['exams']['exams']['records'];
this.questions = this.activeRoute.snapshot.data['question']['question']["result"];
this.questionsOld = this.activeRoute.snapshot.data['question']['question']["result"];
console.log(this.questions)
this.createForm();
}
createForm(): void {
this.editQuestionFG = new FormGroup({
title: new FormControl(this.questions.title, Validators.required),
courseExamId: new FormControl(this.questions.courseExamId, Validators.required),
courseOptions: this._formBuilder.array([])
});
this.setValue(this.questions.courseOptions);
}
createItem(): FormGroup {
return this._formBuilder.group({
optionTitle: new FormControl('', Validators.required),
isCorrect: new FormControl(false, Validators.required)
});
}
setValue(item: Options[]) {
for (let x of item) {
this.editQuestionFG.controls['courseOptions'].setValue({
isCorrect: x.isCorrect,
optionTitle: x.optionTitle
})
}
}
html :
<div class="answer col-lg-12 kt-margin-bottom-20-mobile">
<div formArrayName="courseOptions" class="row m-auto"
*ngFor="let project of editQuestionFG.get('courseOptions').controls; let i = index">
<ng-container [formGroupName]="i">
<div class="col-lg-1 kt-margin-bottom-20-mobile icon remove text-center">
<label (click)="deleteItem(i)"><i class="la la-trash"></i></label>
</div>
<div class="col-lg-8 kt-margin-bottom-20-mobile">
<mat-form-field class="mat-form-field-fluid" appearance="outline">
<mat-label>{{'GENERAL.TITLE' | translate}} *</mat-label>
<input matInput formControlName="optionTitle"
[placeholder]="'GENERAL.TITLE' | translate">
</mat-form-field>
</div>
<div class="col-lg-3 kt-margin-bottom-20-mobile icon">
<mat-radio-group name="radp" aria-label="Select an option"
formControlName="isCorrect">
<mat-radio-button value='true'>صحیح</mat-radio-button>
</mat-radio-group>
</div>
</ng-container>
</div>
<div class="add-Item">
<button (click)="AddItems()" mat-raised-button type="button"
color="accent">{{'COURSE_QUESTION.ADD_NEW_OPTION' |translate}}</button>
</div>
</div>
whats the problem ? how can i solve this problem ????
Try like this:
setValue(item: Options[]) {
const formArray = new FormArray([]);
for (let x of item) {
formArray.push(this._formBuilder.group({
isCorrect: x.isCorrect,
optionTitle: x.optionTitle
}));
}
this.editQuestionFG.setControl('courseOptions', formArray);
}

FormArray ( in Angular6 ) : return empty array

I want to create a dynamic form with form array . When I click this (click)="AddInfoName()" it add form .
I am using this code in html :
<form class="form-line" [formGroup]="addinfoForm" (ngSubmit)="AddRole()">
<div formArrayName="infoName">
<div class="description" *ngFor="let name of InfoFormGroup.controls; let NameIndex=index" [formGroupName]="NameIndex">
<div [formGroupName]="i" class="row">
<label class="form-line"> نام : </label>
<input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="infoName">
<app-filederrors [form]="addinfoForm"
field="getInfoFormGroup(NameIndex)"
nicename="نام">
</app-filederrors>
</div>
</div>
</div>
</form>
And using this code in ts file :
addinfoForm:FormGroup;
infoNameList:FormArray;
infoModel:Productdetail;
constructor(private fb:FormBuilder,private router:Router,private tokenService:TokenstoreService) { }
ngOnInit() {
this.infoNameList = this.fb.array([]);
this.InfoForm();
}
/**
* AddInfoForm
*/
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoName') as FormArray;
}
get InfoFormGroup(){
return this.addinfoForm.get('infoName') as FormArray;
}
public CreateInfoName():FormGroup{
return this.fb.group({
infoName:['',Validators.compose([Validators.required])]
});
}
public AddInfoName(){
this.infoNameList.push(this.CreateInfoName());
console.log('sdkjfghjkdfgh')
}
public RemoveInfoName(index:number){
this.infoNameList.removeAt(index);
}
getInfoFormGroup(index:number):FormGroup{
const formGroup=this.infoNameList.controls[index] as FormGroup;
return formGroup;
}
AddInfo(){
console.log('in form ==>',this.addinfoForm.value)
}
I have tow problem with this code :
1 - when I create a new form it show me this Error :
Error: Cannot find control with path: 'infoName -> 0 -> '
2 - return EmptyArray. I create 5 Form but when I click for add data it show me empty
`infoName: Array(5)
0: {infoName: ""}
1: {infoName: ""}
2: {infoName: ""}
3: {infoName: ""}
4: {infoName: ""}`
Whats the problem ? How can I solve problems?
remove the unnecessary [formGroupName]
should be like this
<form class="form-line" [formGroup]="addinfoForm" (ngSubmit)="AddRole()">
<div formArrayName="infoName">
<div class="description" *ngFor="let name of InfoFormGroup.controls; let NameIndex=index" [formGroupName]="NameIndex">
<div class="row">
<label class="form-line"> نام : </label>
<input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="infoName">
<app-filederrors [form]="addinfoForm" field="getInfoFormGroup(NameIndex)" nicename="نام">
</app-filederrors>
</div>
</div>
</div>
</form>

How intercept submit form?

My project have follow reactive form:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="line">
<input class="title" id="title" placeholder="Заголовок вопроса" type="text" formControlName="title">
</div>
<div class="line">
<textarea class="question" name="question" id="question" placeholder="Текст вопроса" formControlName="question" cols="30" rows="10"></textarea>
</div>
<div class="line">
<div class="tags">
<span class="title">Метки</span>
<span class="tag" *ngFor="let tag of tags">{{ tag }} <span class="delete" (click)="deleteTag(tag)">X</span></span>
</div>
<input class="tag" id="tag" placeholder="Введите тег и нажмите enter" type="text" formControlName="tag" #tag (keyup.enter)="addTag($event, tag.value)">
</div>
<div class="line">
<button class="btn btn-common" type="submit" mat-button [disabled]="form.invalid">
Отправить
</button>
</div>
</form>
This form initialized in component:
private form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
'title': new FormControl('', [Validators.required, Validators.minLength(1)]),
'question': new FormControl('', [Validators.required, Validators.minLength(3)]),
'tag': new FormControl()
});
}
In field #tag user write tagname and press Enter key. And form is submit. But i need cancel form submit after press Enter key.
my attempt:
private addTag(event, tag): void {
console.log(event);
event.preventDefault();
event.stopPropagation();
if(!tag.trim().length) { return; }
this.form.patchValue({tag: ''});
if(this.tags.indexOf(tag) === -1) {
this.tags.push(tag.trim());
}
}
But this does not stop submiting the form. I need cancel submit form after press Enter key
keyup event is too late to catch submit.
I would handle keydown event:
html
(keydown.enter)="addTag($event, tag.value)"
ts
private addTag(event, tag): void {
event.preventDefault();
}
or you can return false
html
(keydown.enter)="!!addTag(tag.value)"
^^^^
convert to boolean
ts
addTag(tag): void {
if(!tag.trim().length) { return; }
this.form.patchValue({tag: ''});
if(this.tags.indexOf(tag) === -1) {
this.tags.push(tag.trim());
}
}
Example

How to add text field dynamically with angular2

Hi guys I'm using angular2 in my project and I'm trying to add an input text dymanically, and it works heres the code :
TS:
initArray() {
return this._fb.group({
title: ['', Validators.required]
})
}
addArray() {
const control = <FormArray>this.myForm.controls['myArray'];
//this.myGroupName.push(newName);
control.push(this.initArray());
}
HTML:
<div formArrayName="myArray">
<div *ngFor="let myGroup of myForm.controls.myArray.controls; let i=index">
<div [formGroupName]="i">
<span *ngIf="myForm.controls.myArray.controls.length > 1" (click)="removeDataKey(i)" class="glyphicon glyphicon-remove pull-right" style="z-index:33;cursor: pointer">
</span>
<!--[formGroupName]="myGroupName[i]"-->
<div [formGroupName]="myGroupName[i]">
<div class="inner-addon left-addon ">
<i class="glyphicon marker" style="border: 5px solid #FED141"></i>
<input type="text" style="width:50% !important" formControlName="title" class="form-control" placeholder="Exemple : Maarif, Grand Casablanca" name="Location" Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)">
<br/>
</div>
</div>
<!--[formGroupName]="myGroupName[i]"-->
</div>
<!--[formGroupName]="i" -->
</div>
</div>
<br/>
<a (click)="addArray()" style="cursor: pointer">+ add text Field</a>
it gives me an error when i add a new text field, any suggestions please??
ERROR Error: Cannot find control with path: 'myArray -> 1 ->
Do not manupulate DOM with AngularJS
In controller create array of inputs
$scope.inputs = [];
$scope.inputs.push({ id: 'input1', value: 'input1' });
$scope.inputs.push({ id: 'input2', value: 'input2' });
$scope.inputs.push({ id: 'input2', value: 'input2' });
<input ng-repeat="input in inputs" ng-model="input.value">
Example

Angular form keep returning false (Angular 2)

I have a form in Angular 2 which I'm validating by the model-driven way. I wanna know how do I change the status from false to true, because I have the rules of validation and even if the user fills everything right, it keeps returning me invalid (false). Here's the HTML code.
<div class="wrap-page">
<form [formGroup]="myForm" novalidate class="form-contato" (ngSubmit)="enviarMensagem(myForm.value, myForm.valid)">
<div class=row>
<div class="col s12">
<h4> Contato </h4>
</div>
<div class="col s12 m12 l6">
<label> Nome: </label>
<input type="text" name="nome" formControlName="nome" class="forms-econ" required placeholder="ex: José Silva">
<div class="div-validar">
<span [hidden]="myForm.controls.nome.valid || (myForm.controls.nome.pristine && !submitted)">
Nome Inválido (mínimo 3 caracteres).
</span>
</div>
</div>
<div class="col s12 l6">
<label> E-mail: </label>
<input type="email" class="forms-econ" formControlName="email" required name="email" pattern="^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$"
placeholder="exemplo#exemplo.com">
<div class="div-validar">
<span [hidden]="myForm.controls.email.valid || (myForm.controls.email.pristine && !submitted)">
E-Mail inválido
</span>
</div>
</div>
<div class="col s12 l6">
<label>Telefone: </label>
<input type="tel" class="forms-econ" name="telefone" formControlName="telefone" pattern="[0-9]" placeholder="(xx)9 9999-99999">
</div>
<div class="col s12 l6">
<label> Motivo do Contato: </label>
<select name="assunto" formControlName="assunto" class="forms-econ">
<option value="motivo_01">Motivo 01</option>
<option value="motivo_02">Motivo 02</option>
<option value="motivo_03">Motivo 03</option>
<option value="motivo_03">Motivo 04</option>
</select>
</div>
<div class="col s12">
<label> Mensagem: </label>
<textarea name="mensagem" formControlName="mensagem" placeholder="Mensagem..." rows="15">
</textarea>
<div class="div-validar">
<span [hidden]="myForm.controls.mensagem.valid || (myForm.controls.mensagem.pristine && !submitted)">
O campo mensagem é obrigatório
</span>
</div>
</div>
<div class="col s12">
<label> ID: </label>
<textarea name="id" formControlName="id" placeholder="Mensagem..." rows="15">
</textarea>
</div>
<h1> {{myForm.valid | json}} </h1> // <-- Here is where I'm printing the status of the form (always return false)
<div class="col s12 right-align">
<input type="submit" value="Enviar" class="btn-form">
</div>
</div>
</form>
</div>
And here is the component.
import { Component, Input } from '#angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '#angular/forms';
import {formContato} from './contato.interface';
import {ContatoService} from './contato.service';
#Component({
moduleId: module.id,
selector: 'contato',
templateUrl: `contato.component.html`,
providers: [ContatoService]
})
export class ContatoComponent {
public contato:formContato;
public myForm: FormGroup;
public submitted: boolean;
public events: any[] = [];
constructor(private _fb: FormBuilder, private mensagemContato:ContatoService) { }
ngOnInit() {
this.myForm = this._fb.group({
nome: ['', [<any>Validators.required, <any>Validators.minLength(3)]],
email: ['', <any>Validators.required],
telefone: ['', <any>Validators.required],
assunto: ['', <any>Validators.required],
mensagem: ['', <any>Validators.required],
id: ['']
})
}
enviarMensagem(model: formContato, isValid: boolean) {
this.submitted = true;
console.log(model, isValid); // -< another way to print the status of the form (always false)
}
}
Thanks in advance :)
Your problem is with the e-mail and phone validation. They always validate as false.
Since you are using a reactive form, I would suggest you move your pattern checks to your build of the form, e.g:
email: ['', [<any>Validators.required, Validators.pattern(....)]],
Then I would assume that you want to inform right from the beginning that fields are required. This can be done in quite a few ways, here I show two possible solutions:
<span *ngIf="myForm.get('nome').hasError('required')">
Name required!
</span><br>
or:
<span *ngIf="!myForm.controls.nome.pristine">
Name required!
</span><br>
and as mentioned in other answer, you need not to pass the myForm.valid in the submit.
I made a Plunker for you, where I set another e-mail validation:
EMAIL_REGEXP = '^[a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$';
and just a random phone number validation, since I wasn't sure exactly what kind of number validation you need. This one checks that the phone number only contains numbers.
If you want you could also disable the submit button if the form is not valid:
<input [disabled]="!myForm.valid" type="submit" value="Enviar" class="btn-form">
but that is of course up to you! :)
Hope this helps!
In Angular 2 , its not required to pass the valid entity on (ngSubmit) , just pass the required form name give to the form group directive .
(ngSubmit)="enviarMensagem(myForm)"
enviarMensagem({model, valid }: {model: Object, valid: boolean}) {
this.submitted = true;
console.log(model, valid);
}

Categories