To create a component dynamicly.
1. Add a container with ref:
@Component({ selector: 'app-root', template: ` <div> <div #entry> <!-- We want to create auth-form component inside this div--> </div> </div> ` })
2. View this container as ViewContainerRef.
@ViewChild('entry', {read: ViewContainerRef}) entry: ViewContainerRef;
3. We need ComponentFactoryResolver:
constructor(private resolver: ComponentFactoryResolver) { }
4. We will create compoennt after content init:
export class AppComponent implements AfterContentInit{ ngAfterContentInit() { } }
5. Create factory by using resolver:
ngAfterContentInit() { const factory = this.resolver.resolveComponentFactory(AuthFormComponent); }
6. Create component by using viewContainerRef:
ngAfterContentInit() { const factory = this.resolver.resolveComponentFactory(AuthFormComponent); this.entry.createComponent(factory); }
7. Make sure, you add entryComponent:
@NgModule({
declarations: [
AuthFormComponent,
AuthRememberComponent,
AuthMessageComponent
],
imports: [
CommonModule,
FormsModule
],
exports: [
AuthFormComponent,
AuthRememberComponent
],
entryComponents: [
AuthFormComponent
]
})
// app.component: import {Component, ViewContainerRef, ViewChild, ComponentFactoryResolver, AfterContentInit} from '@angular/core'; import { AuthFormComponent } from './auth-form/auth-form.component'; import { User } from './auth-form/auth-form.interface'; @Component({ selector: 'app-root', template: ` <div> <div #entry> <!-- We want to create auth-form component inside this div--> </div> </div> ` }) export class AppComponent implements AfterContentInit{ @ViewChild('entry', {read: ViewContainerRef}) entry: ViewContainerRef; constructor(private resolver: ComponentFactoryResolver) { } ngAfterContentInit() { const factory = this.resolver.resolveComponentFactory(AuthFormComponent); this.entry.createComponent(factory); } loginUser(user: User) { console.log('Login', user); } }