Home Angular4 + TemplateOutlet + using template variable in component
Reply: 0

Angular4 + TemplateOutlet + using template variable in component

user2075 Published in May 21, 2018, 9:17 am

In angular4, I'm trying to use ngTemplateOutlet directive to make my component more reusable. And I'm wondering if something it's possible.

Lets take this exemple :


  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
export class UserComponent implements OnInit {

  @ContentChild('userInfos', { read: TemplateRef }) userInfosTemplate;

  public ctx: any = { firstname: 'Jhon', lastname: 'Doe' };

  constructor() { }

  ngOnInit() {



<ng-container *ngTemplateOutlet="userInfosTemplate;context:ctx"></ng-container>


  selector: 'app-root',
  templateUrl: 'app.component.html'
export class AppComponent {


  <ng-template #userInfos let-firstname="firstname" let-lastname="lastname">
    <p>Firstname : {{firstname}}</p>
    <p>Lastname : {{lastname}}</p>

So for the demonstration purpose, I'm building an UserComponent that will display the firstname and the lastname of an user. To make my component more reusable I use the ngTemplateOutlet directive to allow the Upper component decide how he want to display theses two fields.

Here, how can I use this username in the appComponent ? Let's say, I want to check if the firstname is "bob" and in that case I want to log the lastname, or I want to save this in the session, or watever that can't be accomplished in the html file ?

Maybe is there a way to get this var from the TS file, or maybe I can in some way, call a function of my component when this ng-template is displayed ?

If you have any hint, Thanks

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.389004 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO