Neu in Angular 4 - Dynamic Components

19.05.2017Stefan Welsch
Mobile Angular Hands-on

With the new ngComponentOutlet directive it is now possible to create dynamic components in a declarative way. Before, it was complex and time-consuming to create dynamic components because you had to write a lot of code yourself.

Now using the ngComponentOutlet directive just got a lot easier!

In the following example, the user should be greeted accordingly. If it is the first visit to the page, a different greeting should be displayed, as for a recurring visit.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Component({
    selector: 'app-first-time-visitor',
    template: '<h1>Welcome to b-nova!</h1>',
})
export class FirstTimeVisitorComponent {}

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

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

    ngOnInit() {
        if(!this.user.isfirstVisit){
            this.welcome = RepeatingVisitorComponent;
        }
    }
}

In the application we define the ngComponentOutlet directive with the welcome reference. This reference is initialized with the FirstTimeVisitorComponent. The ngOnInit then checks whether it is the first or a recurring visit. In the case of a returning visitor, the welcome reference is set to the RepeatingVisitorComponent. The returning visitor receives the message _Welcome Back to b-nova! _ Instead of _Welcome to b-nova! _.


This text was automatically translated with our golang markdown translator.

Stefan Welsch

Stefan Welsch – Pionier, Stuntman, Mentor. Als Gründer von b-nova ist Stefan immer auf der Suche nach neuen und vielversprechenden Entwicklungsfeldern. Er ist durch und durch Pragmatiker und schreibt daher auch am liebsten Beiträge die sich möglichst nahe an 'real-world' Szenarien anlehnen.