ngIf在包含动态生成的compoent的div上

时间:2017-11-06 12:12:39

标签: angular2-template angular2-directives

我有一个动态生成的组件,它在运行时生成。以下是.ts文件

`@ViewChild(TermsheetDirective) termHost: TermsheetDirective;
    @Input() term;
    @Input() title = '';
    @Input() Qnumber = '';
    @Output() result = new EventEmitter<any>();
    section_title = '';
    number = '';
    component = [];
    show = false;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {

    }
    ngOnInit() {
        this.number = this.Qnumber;
        this.section_title = this.title;
    }


    ngAfterViewInit() {
    }
    ngAfterContentInit() {

    }
    loadcomponents() {
        console.log(this.termHost);
        for (let j = 0; j < this.term.components.length; j++) {
            let termItem = this.term.components[j];
            let componentFactory = this.componentFactoryResolver.resolveComponentFactory(termItem.component);
            let viewContainerRef = this.termHost.viewContainerRef;
            let componentRef = viewContainerRef.createComponent(componentFactory);
            (<TermComponent>componentRef.instance).data = termItem.data;
            this.component[j] = componentRef;
        }
    }
    getdata() {
        let output = [];
        for (let i = 0; i < this.component.length; i++) {
            let temp = {
                slug : this.section_title,
                type : this.component[i].type,
                value : this.component[i]._component.getdata()
            };
             output[i] = temp;
        }
        this.result.emit(output);
        return output;
    }
    showcomp() {
        console.log("In if");
        this.show = true;
        this.loadcomponents();

    }
    hidecomp() {
        this.show = false;
    }`

以下是我的HTML

`<div class="main">
  <div class="div_for_ques">
    <div class="question">
      <div class="number">
        {{number}}
      </div>
      <div class="textbox">
        {{section_title}}
      </div>
        <div class="arrow" *ngIf="!show">
            <a (click)="showcomp()" class="glyphicon">&#xe080;</a>
        </div>
        <div class="arrow" *ngIf="show">
            <a (click)="hidecomp()" class="glyphicon">&#xe080;</a>
        </div>
    </div>
    <div class="sec_two" *ngIf="show">
      <ng-template term-host></ng-template>
    </div>
  </div>
</div>`

我希望包含动态生成的组件的div仅在单击某个按钮时才会出现。但是我有以下回复。enter image description here

但是当我试图在没有ngIf的情况下显示这个div时它工作正常。但是使用ngIf termHost是未定义的!有人可以解释这里发生的事情!

1 个答案:

答案 0 :(得分:1)

好吧,您在更改检测周期完成之前尝试引用 viewContainerRef ,这就是您收到该错误的原因。

对此有多个解决方案,您可以使用 ViewChild 的setter,在* ngIf变为true后将调用一次

e.g

@ViewChild('') set content(x:x) {
this.x = x;

}

OR 您可以手动注入变化检测器

constructor(private changeDetector : ChangeDetectorRef) {}

然后,您可以在单击按钮后调用它

this.changeDetector.detectChanges();

OR 您还可以使用 QueryList 来达到相同的效果,因为您可以订阅更改

请将这些技巧应用于您的逻辑以解决您的问题