Welcome folks today in this blog post we will be using the ng-content
directive to pass dynamic
data to components and implement the content projection
in typescript in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command as shown below
ng new sampleproject
cd sampleproject
And after that you will see the below directory
structure of the angular app as shown below
Now we need to create the child
component by executing the below command
ng g component components/child
Now we need to copy paste the below code inside the app.component.html
as shown below
app.component.html
1 2 3 4 5 |
<h1>This is parent component</h1> <app-child> <h1 id="heading">This is dynamic heading</h1> <p class="sample">This is dynamic paragraph</p> </app-child> |
As you can see in the above html code we have the h1
heading inside the parent component. And then we are including the app-child
child component and inside it we are passing the dynamic
data to the child component. And also we are attaching the id
and the class
selectors to the html
elements.
Now we can include the content
passed from the parent to the child
component using the ng-content
directive as shown below in the child.component.html
file
child.component.html
1 2 |
<p>child works!</p> <ng-content></ng-content> |
As you can see in the above html
code we are including the entire
data passed from the parent to the child
template. Now we can target the individual
elements using the select
attribute as shown below
1 2 3 |
<p>child works!</p> <ng-content select=".sample"></ng-content> <ng-content select="#heading"></ng-content> |