.ts
import { Component, OnInit } from '@angular/core';
import { HelloServiceService } from 'src/app/hello-service.service';
import { FormBuilder, FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
@Component({
selector: 'app-say-hello',
templateUrl: './say-hello.component.html',
styleUrls: ['./say-hello.component.css']
})
export class SayHelloComponent implements OnInit
{
hello = {
greetings: ''
}
objForm: FormGroup;
ordersData = [
{ id: 100, name: 'order 1' },
{ id: 200, name: 'order 2' },
{ id: 300, name: 'order 3' },
{ id: 400, name: 'order 4' }
];
constructor( private objHelloService: HelloServiceService, private formBuilder: FormBuilder )
{
this.objForm = this.formBuilder.group({
orders: new FormArray([])
});
this.addCheckboxes();
}
private addCheckboxes()
{
this.ordersData.forEach((o, i) => {
const control = new FormControl(i === 0); // if first item set to true, else false
(this.objForm.controls.orders as FormArray).push(control);
console.log("QQQQQQQQQQQQ")
});
}
submit()
{
const selectedOrderIds = this.ordersData
.filter(i => i !== null) //Filter array of orders by null check
.map(v => v.id) //Get only ids out of array of orders
console.log(selectedOrderIds) //[100, 200, 300, 400]
}
ngOnInit(): void { }
submitted = false
saveHello()
{
const data = {
greetings: this.hello.greetings
};
this.objHelloService.create(data).subscribe(
response => {
console.log(response);
this.submitted = true;
},
error => {
console.log("From say-hello.component.ts: ",error);
}
);
}
newHello()
{
this.submitted = false;
this.hello = {
greetings: ''
};
}
}
.html
<form [formGroup]="objForm" (ngSubmit)="submit()">
<label formArrayName="orders" *ngFor="let order of objForm.value.orders.controls; let i = index">
<input type="checkbox" [formControlName]="i">
{{ordersData[i].name}}
</label>
<button>submit</button>
</form>
As you can see, addCheckboxes is the function where data is getting pushed in the form object.
What is the way to access this from html?
I intend to display checkboxes on the browser. There are no checkboxes being displayed. Please tell me what is the proper way to write the for loop in html.
asked Jan 22, 2021 at 4:27
Aquarius_Girl
23.2k72 gold badges251 silver badges448 bronze badges
1 Answer 1
You need to add following in your .ts
get objFormArray(): FormArray {
return (<FormArray>this.objForm.get('orders'));
}
in your HTML you can say
*ngFor="let order of objFormArray.controls"
answered Jan 22, 2021 at 5:02
Devang Patel
1,8739 silver badges24 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Aquarius_Girl
Please explain what was I doing previously in my code and why it was failing. I am new to do.
Devang Patel
The way you have written in HTML objForm.value.orders.controls was wrong. You will never find controls in value. Try to console.log(objForm) after fillup data and you will get idea
default