1

I have an angular app which for all intensive purposes is order pad.

There is an order entry component, which has say two children (for example purposes):

|-order_entry.component.ts // selector <orderentry_line></orderentry_line>
  -name_component.ts // selector <name></name>
  -quanity_component.ts // selector <qty></qty>

Now when my application first fires up, there are no instances of order_entry.component.ts loaded, I have a button that on click should load the first instance of this component (with an index so I can reference it)

So when a new instance of order_entry.component.ts is requested it updates my HTML with a new instance of:

<orderentry_line></orderentry_line>

Which then in turn creates:

<name></name>
<qty></qty>

Which would create something along the lines of:

<!-- index is the component number generated in order -->
<input type=text name="name_entry" (ngModelChange)="storeNameValue($index, $event)">
<input type=text name="qty_required" (ngModelChange)="storeQtyValue($index, $event)">

So 1 would be the index (for the first component loaded), so multiple instances of the order_entry component could work in harmony.

Also, I need to be able to delete certain components if required, so lets say I created 4 instances, I would need to be able to delete/remove one component on user action.

So far I have adapted some code from this tutorial and come up with this plunker which shows creating multiple instances of one component, but I cannot seem to update the index value correctly (I imagine I could use a global stream service to store this value and relay it) but I wasn't sure if this was the correct way to achieve this (based on my use case).

I have looked at this very detailed answer and it is helpful, but it does not extend to quite what I am looking to achieve.

1 Answer 1

1

Just maintain the components in an array:

export default class DynamicComponent {
  components = [];

  delete(i:number) {
    this.components[i].destroy();
    this.components.splice(i, 1);
  }

  @Input set componentData(...) {
    ...
    this.components.push(component);
  }
<div *ngFor="let c of components, let i=index">
  {{c.instance.c}} - {{c}} 
  <button (click)="delete(i)">delete</button>
</div>

Plunker example

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

9 Comments

Thanks Gunter, that's exactly what I was looking for.
Hi Gunter, how can I call the delete component function from within itself, rough example of what I am trying to achieve: plnkr.co/edit/ljUcejh4DsEPUfqRrjxh?p=preview
Would I be best of making DynamicComponent a Service?
I don't see why? What's your reasoning?
Simple fix for now seems to be: "component.instance['dynamic'] = this;" thanks again for the help.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.