Why ng-content selector is not working inside *ngFor

前端 未结 6 1108
梦如初夏
梦如初夏 2020-12-21 18:06

Here is the stackblitz code.

As you can see

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-21 18:37

    First lets see what projection/ngContent is.
    Projection is a very important concept in Angular. It enables developers to build reusable components and make applications more scalable and flexible.

    In more simple words it helps in adding content dynamically which can come from server as html or text inside the component without creating DOM node like document.createtextnode().

    Refrence for projection: https://angular-2-training-book.rangle.io/handout/components/projection.html

    Projection is similar to angularjs transclusion in directives. https://docs.angularjs.org/api/ng/directive/ngTransclude

    Lets jump to your problem.
    That's right we need two loops for repeating content in Odd and even numbers acc. to your requirement. reason: ngFor adds new instance of same template in DOM.

    Working code
    https://stackblitz.com/edit/angular-ymznfu?file=app%2Fapp.component.html

    Example:

    App.component.html

    
        //this will work
         
      {{number[1]}}

    child.component.html

    
    

    Above example will work reason, We are projecting outermost dom node in ngContent.

    You can try projecting below code

    app.component.html

     
            
                
            
        
    

    above code will not project reason Angular checks only the outermost node available in the component i.e the reason in your code

      Something

    is projecting and others not.

提交回复
热议问题