angular 怎么样在组件模板中输出子组件(以获取到子组件对象)

问题描述

我现在需要控制子组件的显示方式,目前已经获取到子组件component的对象实例,但是我怎么把这个对象显示在父组件的模板中呢?

问题出现的环境背景及自己尝试过哪些方法

<ng-template [ngComponentOutlet]="child[0]"></ng-template>这样不得行

相关代码

import { Component, OnInit, ViewContainerRef, TemplateRef, ContentChildren, AfterViewInit } from '@angular/core';
import { ISelectItem } from './item-interface';
@Component({
  selector: 'zzj-table-tool-select',
  templateUrl: './table-tool-select.component.html',
  styleUrls: ['./table-tool-select.component.scss']
})
export class TableToolSelectComponent implements OnInit,AfterViewInit {
  children: ISelectItem[] = [];
  @ContentChildren('child') child;
  constructor() { }

  ngOnInit() {
  }
  public addItem(item: ISelectItem) {
    this.children.push(item);
  }
  ngAfterViewInit() {
    console.log('--------');
    console.log(this.child)
  }
}
阅读 3.3k
2 个回答

语法糖:

<ng-container *ngComponentOutlet="ctrl"></ng-container>

直接引用子组件类,不用类实例。

看下官网

ng-content
不对啊,你没输出怎么获取的实例?
还是说你只写了

@ContentChildren('child') child;

但模板中没有与之对应的代码?这样是获取不到实例的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进