3

I am new to Angular 2. I have seen a component is always coupled with a view template like

@Component({
  selector: 'page-sample',
  templateUrl: 'sample.html',
  providers: []
})

Can we reuse an Angular 2 component to different template dynamically?

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
Atanu Mallick
  • 266
  • 4
  • 7
  • you want to use single template in two components ? – Pardeep Jain Mar 20 '17 at 06:40
  • 2
    @PardeepJain I think he is referring to using single component with different templates.. – Suraj Rao Mar 20 '17 at 06:43
  • http://stackoverflow.com/questions/31692416/dynamic-template-urls-in-angular-2 – Suraj Rao Mar 20 '17 at 06:43
  • Single Component - Different Templates. But based on what? Different URL will be used for different template but same component? Or Different Data loaded via $http call will show different template but same component? Based on the requirement best approach can be taken. – Partha Sarathi Ghosh Mar 20 '17 at 07:54

1 Answers1

7

This does not answer the question directly, but I want to suggest a method where you can have a different view using (almost) the same component.

I usually make another component, and let it extend the base component in order to re-use the same functionality.

//base component with functionality
@Component({
  selector: 'page-sample',
  templateUrl: 'sample.html',
  providers: []
})
export class BaseComponent{
}

Create a new component that extends BaseComponent, but can use a different view.

// another component with a different view.
@Component({
  selector: 'another-page-sample',
  templateUrl: 'another-sample.html',
  providers: []
})
export class AnotherComponent extends BaseComponent{
}
John
  • 10,165
  • 5
  • 55
  • 71
  • 1
    You need to use `extends`, not implements if BaseComponent has a constructor or any methods. – Aluan Haddad Mar 20 '17 at 08:58
  • Regardless, I haven't found a better solution than this, and this solution certainly works, but it is a hack to work around the fact that support for a common, simple use case is simply missing from Angular 2. – Aluan Haddad Mar 20 '17 at 09:01
  • 1
    Maybe [this post](http://stackoverflow.com/questions/31692416/dynamic-template-urls-in-angular-2) is what you are looking for? I haven't taken the time to study it myself, but @suraj mentioned it as a comment on the question. – John Mar 20 '17 at 09:04
  • Right, the class factory approach also works (actually I think it might be better here also), its quite elegant in some scenarios but it is inconvenient here as compared to the router based approaches that were common in AngularJS (both the ng-route and ui-router packages supported it) where templates and controllers could be mixed and matched in a first class way. – Aluan Haddad Mar 20 '17 at 09:08