1

I'm writing an Angular 5 app at the moment where I need to use a FormBuilder array for one of the properties. I have one property which states how many controls should be in the array but can't find any resources on how to create a FormBuilder array with that many controls.

The form looks something like this:

this.Form = this.fb.group({
    ...
    noOfControls: null, // 
    controls: <-- fb.array
});

What would be the best way to go about doing this?

1
  • What about a function that returns a FormArray containing all the controls that you need? Commented Apr 15, 2018 at 0:15

1 Answer 1

2

you should create a observable that listen the to the noOfControls values, inside this observable you should call a method that add or remove controls to your formArray based on the length of your current control

let say this is your form

this.Form = this.fb.group({
    noOfControls: this.fb.control(null,[]),
    controls: this.fb.array([])
});

to listen the changes of your control you can use

this.Form.valueChanges.map(values=>values.noOfControls).distinctUntilChanged()
.subscribe((num)=>{
     ...
    })

to handle in a easy way your controls inside the array you can create a method that return the control as array

get control() {
 return this.form.get('controls') as FormArray
}

inside the subscription you should have some kind of logic that analyze every time that the number change the length of your control array

if(this.control.length > num) {
 ... remove one control array item
}
if(this.control.length < num) {
 ... add the differences in the number of control items
}

to remove the last element you can use the removeAt(index: number) method from the FormArray class

to add a new form control you can use push(control: AbstractControl)

let me know if you need more help

Sign up to request clarification or add additional context in comments.

3 Comments

That's perfect, thanks so much! I wrapped the if statement in a for loop for the difference between the length and the num so that if a user puts a number that's more than 1 away from the length it will appropriately remove or add extra elements. Originally I would have used a while loop but that seemed to cause it to infinite loop.
Slight issue, seeems like if the user types in values too quickly (or indeed a two digit number) the program goes crazy. I'm assuming it's because the code is running multiple times before it finishes. Is there anyway to wait for the user to stop typing before executing the code?
I've ended up scrapping the idea because it has too many issues, but I'll leave the question up for others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.