Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 component with multiple views

Tags:

angular

How can I give an Angular 2 component multiple views\view templates?

Do I have to use ng-content? Which is not exactly the function I want. Maybe a component property that specifies the template url, but then how to change the view\template in the component class?

like image 614
rethenhouser2 Avatar asked Aug 06 '15 04:08

rethenhouser2


2 Answers

Today also think about this problem. I "invent" this solution http://plnkr.co/edit/FYVwbBwSnqWRcvAVz3wh?p=preview . May be it helps You in future.

export class MyModel {
  lala;
  constructor() {
    this.lala = "llaala";
  }
  appendToLala(param: string){
    this.lala += param;
  } 
}

@Component({
  selector: 'c1',
  template: `<div><h2>Hello {{lala}}</h2></div>`,
})
export class Component1 extends MyModel {
  constructor(){
    super();
    this.appendToLala(" bebebe");
  }
}


@Component({
  selector: 'c2',
  template: `<div><h2>Hello {{lala}}</h2></div>`,
})
export class Component2 extends MyModel {
  constructor(){
    super();
    this.appendToLala(" nenene");
  }
}

The idea is to create an abstract component model and use it as @Component's parent. And if needed, You can create a tree from models and @Component class will always be a leaf in this tree.

like image 76
karina Avatar answered Sep 26 '22 20:09

karina


The ng-content is to be used to define where you want the content of your component to go, explanation follows :

Say you define your own component with its template and a selector 'my-cmp', if you use it as such : <my-cmp><div>content</div></my-cmp>, the div inside your component must go somewhere, that is what you define in the template when you implement my-cmp. Say : <h1>my component title</h1><ng-content></ng-content> your div will go where the ng-content is placed.

Now if you want to have multiple views I believe it's a design issue, and it would most likely be two different components, and then a parent container would contain them both. This parent container could communicate with your service and give your child components the model they need to display themselves. They could emit an event when the user does something, that the parent catches, triggers a service call, and feeds them the updated model through data binding.

Or if you want to display one or the other maybe it can be handled with routes ?

Or a last way would be a ng-if, if you have a certain state in your model then display one child component, otherwise display the other.

If you are a bit more specific about the need you have I could mock up some code.

like image 20
Arnaud Boeglin Avatar answered Sep 25 '22 20:09

Arnaud Boeglin