Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple ng-content not working in angular 2

I try to transclude content. I have the following markup for the component:

<body>
    <bn-menu>
      <span>test</span>
      <p>I am content</p>
    </bn-menu>
  </body>

And the following component:

import { Component } from '@angular/core';
@Component({
  selector: 'bn-menu',
  template: '<div><div>Jo</div><ng-content></ng-content></div>'
})
export class MenuComponent { }

But only "Jo" gets displayed and not "test" or "I am content". What am I doing wrong?

like image 500
Jan Hommes Avatar asked Oct 10 '16 12:10

Jan Hommes


People also ask

Can I style ng-content?

If you want to style the projected content within <ng-content>, you can do so using :host and ::ng-deep to apply styling to all nested elements within the <contact> component.

What is Contentprojection?

Content projection is a pattern in which you insert, or project, the content you want to use inside another component. For example, you could have a Card component that accepts content provided by another component.

How do you use NG-content?

The ng-content is used when we want to insert the content dynamically inside the component that helps to increase component reusability. Using ng-content we can pass content inside the component selector and when angular parses that content that appears at the place of ng-content.

What is the difference between Ng-content ng container and ng-template?

ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.


1 Answers

It seems you are trying to display the content in the Root component, Content within the Root component are typically used for displaying content used while angular is booting up.

If you can wrap bn-menu inside some other root component it should work.

Check this SO question Component with <ng-content>

like image 161
Madhu Ranjan Avatar answered Oct 19 '22 19:10

Madhu Ranjan