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.