动态添加组件角度2

时间:2017-11-11 02:10:08

标签: angular typescript

我正在尝试在Angular 2中实现一个ComponentContainer,以便您可以动态添加其他组件。 我将EditQuestionComponent添加到DesignComponent中。但是当我尝试将另一个组件SingleChoiceComponent添加到刚刚在事件ngAfterViewInit中添加的EditQuestionComponent时,我的问题。但ViewContainerRef未定义。 这是我的代码 编辑question.html

async

编辑question.ts

 <div class="choice-section clearfix">
            <div class="single-choice-section clearfix" *ngIf="questiontype == 'MC'">
                <div class="single-choice-inner clearfix">
                    <div #singlechoice></div>
                </div>
            </div>
        </div>

design.html

import {Component,Input, NgModule, OnInit, AfterViewInit, ViewChild, ViewContainerRef ,ComponentFactoryResolver} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {QuestionTypeService} from '../../services/questiontype.service';
import {SingleChoiceComponent} from '../choice-single/choice-single.component';
import * as $ from 'jquery/dist/jquery.min.js';

@NgModule({
    imports : [NgModule, FormsModule],
    declarations : [EditQuestionComponent, SingleChoiceComponent],
    entryComponents :[SingleChoiceComponent],
    bootstrap :[EditQuestionComponent]
})
@Component({
    selector : 'edit-question',
    templateUrl : './editing-question.component.html',
    styleUrls: ['./editing-question.component.css']
})

export class EditQuestionComponent{
    @Input() lstChoice : any;

    public lstQuestionType : any;
    public questiontype : string;
    public lstChoiceSingle : any;
    public countChoice : any;

    @ViewChild("singlechoice", { read: ViewContainerRef }) singlechoice: ViewContainerRef;

    constructor(private _qt: QuestionTypeService,private viewContainer: ViewContainerRef,
        private _cr: ComponentFactoryResolver){
    }
    ngOnInit() {
        //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
        //Add 'implements OnInit' to the class.
        this._qt.get_all().subscribe((data:any)=>{
            this.lstQuestionType = data.Data;
            this.questiontype = this.lstQuestionType[0].questiontype_code;
        });

    }  
    public addChoice(lstChoice : any){
        this.lstChoiceSingle = lstChoice;
    }
    ngAfterViewInit() {
        //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
        //Add 'implements AfterViewInit' to the class.
        let cmpFac = this._cr.resolveComponentFactory(EditQuestionComponent);
        this.singlechoice.createComponent(cmpFac);
    }

}

design.ts

<div class="edit-question-cover clearfix">
  <div class="col-md-push-3 col-lg-push-3 col-md-9 col-lg-9" >
      <!-- <edit-question [lstChoice]="lstchoice"></edit-question> -->
      <div #childContainer>

      </div>
  </div>

</div>

0 个答案:

没有答案