【问题标题】:Angular Access inner component of ng-templateng-template 的 Angular Access 内部组件
【发布时间】:2017-10-01 13:12:21
【问题描述】:

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

<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 组件:

@ViewChild('top') topComponent: TopComponent;

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

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

PS。我知道我可以创建另一个组件,使用它而不是 &lt;ng-template&gt; 并从中访问所有必要的子组件。但这可以通过某种方式避免吗?

【问题讨论】:

  • 不应该是@ViewChild('#top')吗?
  • @Meir,您的意思是访问#top 组件?没有# 符号也可以正常工作。

标签: angular components


【解决方案1】:

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

这里是填写代码: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);
    }
  }

【讨论】:

  • 感谢您的回答,朱莉娅。但它说descendants 不能使用。仅允许 read: any。我需要一个特殊的库吗?
  • 这个例子似乎在不使用“{descendants: true}”选项的情况下工作,这似乎是无效的配置。编译器给出错误:类型的参数'{后代:布尔值; }' 不能分配给 '{ read?: any; 类型的参数。 }'。对象字面量只能指定已知属性,并且 '后代' 不存在于类型 '{ read?: any; }'。
  • 即使没有descendants: true 也可以工作。重要的是使用ngAfterViewInit not onInit 或构造函数。
  • 这对我不起作用,我得到与@Algis 相同的错误。没有也行不通
  • 后代没有了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-09
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多