ng-template的Angular Access内部组件 [英] Angular Access inner component of ng-template

查看:116
本文介绍了ng-template的Angular Access内部组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个名为TopComponent的组件,其模板如下:

Let's say we have a component called TopComponent with a template like this:

<ng-template #top>
    <inner-selector #inner></inner-selector>
</ng-template>

它的代码很简单:

//... imports ...

@Component({
  // selector, styles etc
})
export class TopComponent implements AfterViewInit {

  @ViewChild('top') topComp : NgbModal;
  // NgbModal is a type provided by some 3rd-party library
  // I can't modify it

  ngAfterViewInit() {
    // let's access the #inner component from here
  }
}

我可以使用以下代码访问#top组件:

I can access the #top component using this code:

@ViewChild('top') topComponent: TopComponent;

如何从同一个类访问#inner组件?

How can I access the #inner component from the same class?

我尝试使用@ContentChild('inner'),但仍然得到undefined.

I tried using @ContentChild('inner') but still getting undefined.

PS.我知道我可以创建另一个组件,使用它代替<ng-template>并从中访问所有必需的子代.但这可以避免吗?

PS. I know I can create another component, use it instead of <ng-template> and access all the necessary children from it. But can this be avoided somehow?

推荐答案

使用后代@ViewChild('inner',{descendants:true})内部:InnerSelector;

Use descendants @ViewChild('inner', {descendants: true}) inner: InnerSelector;

这是填充代码: https://plnkr.co/edit/MtVhHuAtPXZzC7GLOidF?p=预览

 @Component({
    selector: 'inner-selector',
    template:'inner-selector here'
  })
  export class InnerSelector {
    myVar = 0;
  }

  @Component({
    selector: 'my-app',
    template: `
      <div>
        <ng-template #top>
           <inner-selector #inner></inner-selector>
        </ng-template>

       <ng-container [ngTemplateOutlet]="top"></ng-container>
      </div>
    `,
  })
  export class App {
    @ViewChild('inner', {descendants: true}) inner: InnerSelector;
    constructor() {
      this.name = `Angular! v${VERSION.full}`
    }
    ngAfterViewInit() {
      console.log(this.inner);
    }
  }

这篇关于ng-template的Angular Access内部组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆