Neu in Angular 4 - Dynamic Components

19.05.2017 Stefan Welsch
Mobile Tech angular handson

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.

@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 - pioneer, stuntman, mentor. As the founder of b-nova, Stefan is always looking for new and promising fields of development. He is a pragmatist through and through and therefore prefers to write articles that are as close as possible to real-world scenarios.