2

Are there any example as to render different template in a single component based on certain conditions being fulfilled?

given route '/app', i want to render component/template A if the user A is logged in, and render component/template B if user B is logged in

finalight
  • 21
  • 3
  • The simplest solution would be using the conditions inside one template/component. Example: `*ngIf=getUserRole()`. – Petr Nov 14 '16 at 14:27
  • *You should not miss this [How can I use/create dynamic template to compile dynamic Component with Angular 2.0?](http://stackoverflow.com/q/38888008/1679310)* – Radim Köhler Nov 14 '16 at 14:34

2 Answers2

0

One simple solution for this approach is just to use expressions in your template in order to display different content.

For example in your component:

<div *ngIf="userLoggedIn">
  Something
</div>

<div *ngIf="!userLoggedIn">
  Something Else
</div>

There are some tother approaches like in this questions Dynamic template URLs in Angular 2 but it has to do with what exactly you want to show.

If you add a working fiddle/example I can update my answer further.

Community
  • 1
  • 1
Vassilis Pits
  • 3,788
  • 4
  • 33
  • 48
0

1- install this library

npm i -D html-loader

============================================================

2- In webpack.config use html-loader for html files

 { test: /\.html$/,  loaders: ['html-loader']   }

============================================================

3- If you use ionic , you can copy webpack.config.js from the path "node_modules/@ionic/app-scripts/config/webpack.config.js" then add the html loader to it

=============================================================

4-If you use ionic In package.json add these lines

"config": { 
    "ionic_bundler": "webpack",
    "ionic_webpack": "webpack.config.ionic.js" 
  },

=============================================================

5-Then you can use it as below

@Component({
  selector: 'page-login',
 // templateUrl:"./login.html"

   template:     function(){
    if(globalVariables.test==2) {

      return require("./login2.html")
    }
    else
    {
      return require("./login.html")
    }
  }(),
})

======================================

6-If there is unresolved error with require function you can put it in declarations.d.ts file as the below :

declare var require: any;

Bahgat Mashaly
  • 510
  • 7
  • 15