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?

4
  • you want to use single template in two components ? Commented Mar 20, 2017 at 6:40
  • 2
    @PardeepJain I think he is referring to using single component with different templates.. Commented Mar 20, 2017 at 6:43
  • stackoverflow.com/questions/31692416/… Commented Mar 20, 2017 at 6: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. Commented Mar 20, 2017 at 7:54

1 Answer 1

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{
}
Sign up to request clarification or add additional context in comments.

4 Comments

You need to use extends, not implements if BaseComponent has a constructor or any methods.
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.
Maybe this post 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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.