0

I have a HTML page as shown in picture. enter image description here

Here "Add Rows" is a button whose functionality is to create an empty row as shown in picture and the user can enter details in the boxes provided.

As I am new to angular 7 pls suggest me which is the best way to do this and add a sample code snippet if possible.

2
  • 1
    stackoverflow.com/help/how-to-ask Commented May 13, 2019 at 11:15
  • You should create a @Component containing an @Output, and when this output emits, the parent component should then be able to add the new element to your collection. Commented May 13, 2019 at 11:26

1 Answer 1

1

the easies way in my eyes is to create a variable like

rowCount = [];

this is an array.

In your html you create an ngFor look where you iterate over the array and created a number of lines you have in your array.

addRow() is just pushing an item, what could be a model or so to the array. What will result as render of new line.

the ts code

criteriaFormArray = this.formBuilder.array()
....
private insertInFormArray(control: AbstractControl) {
    this.criteriaFormArray.push(control);
  }

the rendering

<div
    formArrayName="criteria"
    *ngFor="
      let item of criteriaFormArray.controls;
      let i = index;
      let first = first;
      let last = last
    ">....</div>

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

6 Comments

Since ngFor creates dynamic variables when iterating, the model binding with ngModel faces some issues that are very hard to understand for a beginner. Maybe you should explain more in depth your solution, or provide another one ?
@trichetriche I suggest you to take a look at dynamic forms with angular. You can create FormGroups etc for this. It is a big topic to cover here. there are great tutorials out there :) angular.io/guide/dynamic-form
I know the dynamic forms. As you said, they don't work with template driven forms, which isn't specified in your answer (to someone who starts Angular and probably doesn't even know reactive forms). That was my actual point !
@trichetriche I have added some examples to my answer. I can't post a working example, there are to many dependencies. Each line is a a custom controll in my case.
That's all I was asking @Fribu !
|

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.