0

I have a form with a single text box that allows 35 characters. I want the user to be able to click a button to add another identical textbox to the form below which also allows 35 characters. The add button would only allow 3 more text boxes to be added. Is there an easy way to do this? Here is the code of what I have so far. My first idea was to just have the same code replicated 4 times and hide it until the button was clicked but was wondering if this could be done in an array or some kind of function to avoid so much duplication. Thanks!

HTML

<div>
  <h2>Title</h2>

     <div>
       <mat-form-field appearance=outline>
         <mat-label>Title</mat-label>
         <input matInput formControlName="Title" maxlength="35" required>
       </mat-form-field>
     </div>

  <button>Add Line</button>

</div>
BDev14
  • 9
  • 7
  • 1
    I don't have time to write a detailed answer but I can point you in the right direction: FormArrays - https://angular.io/api/forms/FormArray – Steve Jun 24 '20 at 20:20

1 Answers1

0

Based on this and this answer, here is what you need to do:

        count_user_click = 0;
        function addFields() {
            if (this.count_user_click == 3) {
                alert('too many times!');
            }
            else {
                // increase counter
                this.count_user_click += 1;
                var container = document.getElementById("container");
                // get the element with that id
                let clone = document.querySelector('#tobecopied').cloneNode(true);
                // Change the id attribute of the newly created element:
                clone.setAttribute('id', 'new' + this.count_user_click);
                // Append the newly created element on container 
                container.appendChild(clone);
            }
        }
<div>
        <h2>Title</h2>
        <div>
            <mat-form-field appearance=outline id="tobecopied">
                <mat-label>Title</mat-label>
                <input matInput formControlName="Title" maxlength="35" required />
                <br >
            </mat-form-field>
        </div>
        <button onclick="addFields()">Add Line</button>
        <div id="container" />
    </div>

This was the easiest way I could see to achieve what you are looking for.
Good luck!

BatshevaRich
  • 550
  • 7
  • 19