Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One component to bind different template dynamically in Angular-2

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?

like image 606
Atanu Mallick Avatar asked Sep 26 '26 19:09

Atanu Mallick


1 Answers

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{
}
like image 106
John Avatar answered Sep 29 '26 12:09

John