I have an object like this.
types: {
2: {
zoom: true,
select: true
},
4: {
zoom: true,
select: true
},
}
Is it possible to create this json object from a angular form?
<div formGroupName="types">
<input type="number" matInput placeholder="Type" [(ngModel)]="searchType" i18n-placeholder>
<div [ngModelGroup]="searchType">
<mat-slide-toggle [(ngModel)]="searchType.zoom" color="primary">Zoom</mat-slide-toggle>
<mat-slide-toggle [(ngModel)]="searchType.select" color="primary">Klik</mat-slide-toggle>
</div>
</div>
Sadly it's not possible to change the json but the numbers need to be changable. The form is reactive driven but I could not find a way so I tried template driven but neither way worked out.
Using Angular reactiveForm
and Factory
to build your desire json
object. It is possible to add property
dynamically to your object. But your props name could not be some numbers as you mentioned in your example; If you want something its better to have an array of objects.
So, try something like this:
app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { TypeFactory } from './type.factory.ts';
import { TypeModel } from './app-type.model';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
typesForm:FormGroup;
types: TypeModel[] = [];
constructor(
private formBuilder: FormBuilder,
private typeFactory: TypeFactory,
){}
ngOnInit(){
this.typesForm = this.formBuilder.group({
id: ['', [Validators.required]],
zoom: [''],
select: ['']
});
}
regForm = () => {
let newType = this.typeFactory.createTypeDto(this.typesForm.getRawValues());
this.types = [ ...types, ...newType];
}
}
app.component.html
<form [formGroup]="typesForm">
<input formControlName="id" type="number" matInput placeholder="Type" i18n-placeholder>
<div class="container">
<mat-slide-toggle formControlName="zoom" color="primary">Zoom</mat-slide-toggle>
<mat-slide-toggle formControlName="select" color="primary">Klik</mat-slide-toggle>
</div>
<button class="btn btn-success" (click)="regForm()">Register</button>
</form>
app-type.model.ts
export class TypeModel {
id: number;
zoom: boolean;
select: boolean;
}
app.factory.ts
import { TypeModel } from './app-type.model';
export class TypeFactory {
createTypeDto(
form: any,
): TypeModel {
const model = new TypeModel();
model.id = form.id;
model.zoom = form.zoom;
model.select = form.select;
return model;
}
}