Angular Access inner component of ng-template

不羁的心 提交于 2019-12-30 18:50:43

问题


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?


回答1:


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);
    }
  }


来源:https://stackoverflow.com/questions/43764536/angular-access-inner-component-of-ng-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!