Reputation: 173
Is there any way to declare/use a "template" fragment in angular 2/4? let say I have 2 components with some duplicate section in them and I don't want to make this section a @Component. is there anyway to avoid it? let assume the following fragment :
<div class="col-md-6 no-padding">
<label for="to_date">To</label>
<datetime id="to_date" [(ngModel)]="to_date" [timepicker]="false"
(ngModelChange)="onToDateChanged($event)"
[datepicker]="to_options">
</datetime>
</div>
I don't want to declare this div on each page I need a datetime picker, and I also don't want to make it a @Component. Any suggestion/workaround/help?
Upvotes: 2
Views: 118
Reputation: 3612
One way to do this is to define a template in your parent and pass it to your children using ngTemplateOutlet
.
https://angular.io/api/common/NgTemplateOutlet
Try looking at this article for more information:
http://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
One simple potential solution, close to what you want:
You can define a template in your parent component:
<div #myTemplate>Hello</div>
Then get a reference to it using a ViewChild:
@ViewChild('myTemplate') templateForChild;
You can then pass it to your child:
<your-component [template]='templateForChild'></your-component>
Then accept that as input in your component:
public class YourComponent {
@Input() template: TemplateRef;
....
}
Upvotes: 1