Angular2: Creating child components programmatically

后端 未结 5 1508
心在旅途
心在旅途 2020-12-13 18:20

Question

How to create child components inside a parent component and display them in the view afterwards using Angular2? How to make sure the injectables

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 18:48

    Warning: DynamicComponentLoader has been deprecated in RC.4

    In Angular 2.0, loadIntoLocation method of DynamicComponentLoader serve this purpose of creating parent-child relationship. By using this approach you can dynamically create relationship between two components.

    Here is the sample code in which paper is my parent and bulletin is my child component.

    paper.component.ts

    import {Component,DynamicComponentLoader,ElementRef,Inject,OnInit} from 'angular2/core';
    import { BulletinComponent } from './bulletin.component';
    
    @Component({
        selector: 'paper',
        templateUrl: 'app/views/paper.html'
    
        }
    })
    export class PaperComponent {
        constructor(private dynamicComponentLoader:DynamicComponentLoader, private elementRef: ElementRef) {
    
        }
    
        ngOnInit(){
            this.dynamicComponentLoader.loadIntoLocation(BulletinComponent, this.elementRef,'child');
    
        }
    }
    

    bulletin.component.ts

    import {Component} from 'angular2/core';
    
    @Component({
        selector: 'bulletin',
        template: '
    Hi!
    ' } }) export class BulletinComponent {}

    paper.html

    Few things you needs to be take care of are mentioned in this answer

提交回复
热议问题