New in Angular 4: Dynamic components with *ngcomponentoutlet

- Stefan Welsch

With the new *ngComponentOutlet directive it is now possible to create dynamic components on a declarative way. The old way to create dynamic components was very heavywight and complex, because you have to write a lot of programming code. 
Now with *ngComponentOutlet it is much more easier. The following example shows how to implement a component that recognize if it is a first time visitor or a repeating visitor. Dependent on the type of visitor the corresponding component will be used.

selector: 'app-first-time-visitor',
template: '<h1>Welcome to b-nova!</h1>',
export class FirstTimeVisitorComponent {}

selector: 'app-repeating-visitor',
template: '<h1>Welcome Back to b-nova!</h1>',
export class RepeatingVisitorComponent {}

selector: 'app-root',
template: `
<h1>Hello b-nova Friend</h1>
<ng-container *ngComponentOutlet="welcome"></ng-container>
export class App implements OnInit{
welcome = FirstTimeVisitorComponent;

ngOnInit() {
this.welcome = RepeatingVisitorComponent;

In the App class we define the *ngComponentOutlet with the welcome reference. The welcome reference will be initialized with the FirstTimeVisitorComponent. Then in the ngOnInit method we check if it is a first time visitor, or a repeating visitor. If it is a repeating visitor then we set the welcome reference to the RepeatingVisitorComponent and the user will see the “Welcome Back to b-nova!” message instead of the “Welcome to b-nova!” message.