0

How do I add a field to a reactive form that can dynamically add and delete to a type string array? The implementation I have right now is a FormArray, however it adds to the array as a object rather that just another string in the array. (see code below)

ngOnInit() {
  this.form = this.formBuilder.group({
    user: '',
    directory: '',
    filename: this.formBuilder.array([ this.createItem() ])
  });
}

createItem(): FormGroup {
  return this.formBuilder.group({
    filename: ''
  });
}

7
  • You need to define the form as the class variable in order to access it everywhere! Commented Oct 12, 2018 at 4:21
  • @Exterminator It is declared in the code I just didn't include in the snippet. It works but I'm asking how to implement as adding to an array as a string rather than an object. Commented Oct 12, 2018 at 4:25
  • check this out Reactive Forms in Angular: Dynamically Creating Form Fields With FormArray Commented Oct 12, 2018 at 4:26
  • @Exterminator that is the reference I am using right now.. Is there a way to just add input directly to an array instead of creating a formgroup for the FormArray? Commented Oct 12, 2018 at 4:30
  • yes, you can create template driven form instead of reactive form Commented Oct 12, 2018 at 4:32

1 Answer 1

3

Instead of creating formGroup you can try this

constructor(private formBuilder:FormBuilder){
   this.form = this.formBuilder.group({
    user: '',
    directory: '',
    filename: new FormArray([new FormControl('hai')])
  });

 }

 addFormInput(){
    const form=new FormControl('');
   (<FormArray>this.form.controls['filename']).push(form);
  }

removeFormInput(i){
  (<FormArray>this.form.get('filename')).removeAt(i);
 }

Example:https://stackblitz.com/edit/angular-tvuksw

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

Comments

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.