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

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

问题描述

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

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

代码很简单:

//... 导入 ...@零件({//选择器、样式等})导出类 TopComponent 实现 AfterViewInit {@ViewChild('top') topComp : NgbModal;//NgbModal 是一些 3rd-party 库提供的类型//我不能修改它ngAfterViewInit() {//让我们从这里访问#inner 组件}}

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

@ViewChild('top') topComponent: TopComponent;

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

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

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

解决方案

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

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

 @Component({选择器:'内部选择器',模板:'这里的内部选择器'})导出类 InnerSelector {我的变量 = 0;}@零件({选择器:'我的应用',模板:`

<ng-模板#top><inner-selector #inner></inner-selector></ng-模板><ng-container [ngTemplateOutlet]="top"></ng-container></div>`,})导出类 App {@ViewChild('inner', {descendants: true}) 内部:InnerSelector;构造函数(){this.name = `角!v${VERSION.full}`}ngAfterViewInit() {控制台.log(this.inner);}}

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

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

It's code is simple:

//... 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
  }
}

I can access the #top component using this code:

@ViewChild('top') topComponent: TopComponent;

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

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

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?

解决方案

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

here is fill code: https://plnkr.co/edit/MtVhHuAtPXZzC7GLOidF?p=preview

 @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天全站免登陆