0

I am creating Quora/facebook like comment functionality. But comments can go to any depth. Following is my template:

<ul>
    <li *ngFor="let item of items let i = index">

    <!-- some html code -->
   <button(click)="addComment(item.id,i)">
    <div>
            <ng-template #target></ng-template>           
    </div>

   </li>
</ul>

I am creating dynamic component and for this i have refered this answer.

export class myDynamicComponent {
     @ ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef; 
     constructor(private replyService: ReplyService, private cfr: 
     ComponentFactoryResolver){}

    public addComment(Id:any, index:any){
       this.commentService.getContent(Id)
              .subscribe(data => {
     let compFactory = 
     this.cfr.resolveComponentFactory(myDynamicComponent);              
     let instance=this.target.createComponent(compFactory).instance;
        instance.items=data ;
  }
 }
}

So i am creating dynamic component in #target. I have multiple because it is generating in the loop. The problem with this is that newly created component get attached to first #target and not the current (clicked) #target.

What is the way to solve this?

1 Answers1

0

instead of:

<li *ngFor="let item of items let i = index">

    <!-- some html code -->
   <button(click)="addComment(item.id,i)">
    <div>
            <ng-template #target></ng-template>           
    </div>

   </li>

extract it to separate component like:

<li *ngFor="let item of items let i = index">

   <my-button-click-comment-something-component [sendToIt]="whateverYouNeed">
   </my-button-click-comment-something-component>

</li>

and then in your my-button-click-comment-something-component do dynamic component creation and handling.

dee zg
  • 13,793
  • 10
  • 42
  • 82
  • actually my 'my-button-click-comment-something-component' is the 'myDynamicComponent'. I need to create n number of components. There is no limit of the depth for comments. I followed your suggestions but still can not atach newly created dynamic component to current directive/#target. – Ganesh Wagh Oct 24 '17 at 18:05
  • i don't think so. The whole point is that `*ngFor` and `#target` are not in the same template. – dee zg Oct 24 '17 at 18:08
  • could you please elaborate more on your comment? Because even if I separate out component I still need to load future components in – Ganesh Wagh Oct 24 '17 at 18:22
  • yes exactly but then you have just one `#target` where you need to make instance of your component – dee zg Oct 25 '17 at 04:22