.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.
question from:
https://stackoverflow.com/questions/65839291/how-to-access-angulars-form-array-in-html 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…