Angular2 child component as data

前端 未结 1 1568
渐次进展
渐次进展 2020-11-28 11:24

Let\'s say I have two components: parent and child. The HTML would look like this:


    

        
1条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 12:11

    For projecting content to an element (transclusion) you would need the element like

    @Component({
      selector: 'parent',
      directives: [ChildComponent], // needed?
      template: `
        

    {{title}}

    ` })

    but that won't work for your use case because doesn't produce content, it only projects it (works as a placehoder where children are displayed within your components template.

    Even though *ngFor would produce 3 elements, the children would only be displayed once in the first element.

    allows to use selectors like

    
    

    where a template like

    `

    would result in

    Welcome

    • Chris is on the Blue Team

    A more flexible and powerful approach explained in Binding events when using a ngForTemplate in Angular 2 (from @kemsky s comment)