【问题标题】:Retrieving a content projected inside a component into a variable将组件内投影的内容检索到变量中
【发布时间】:2019-05-29 22:10:10
【问题描述】:

我正在尝试将角度组件投影的内容检索到打字稿变量中。

我尝试使用 @ViewChild 装饰器检索内容并使用控制台 log() 显示它,但出现错误。

以下是我在各个文件中写的代码:

app.component.html(父组件)

<app-test>
    <div class="t1">
        Test Data 1
    </div>
    <div class="t2">
        Test Data 2
    </div>
</app-test>

test.component.html(子组件)

 <div #tt>The following data was passed to this component:</div>
    <ng-content select=".t1" #t1></ng-content>
    <ng-content select=".t2" #t1></ng-content>

test.component.ts(子组件脚本)

import { Component, OnInit, ViewChildren, AfterContentInit, ElementRef } 
from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: [ './test.component.scss' ]
})
export class TestComponent implements AfterContentInit {

  @ViewChildren('t1') t1: ElementRef;
  @ViewChildren('t2') t2: ElementRef;
  @ViewChildren('tt') tt: ElementRef;
  constructor () { }

  ngAfterContentInit() {
      console.log(this.t1.nativeElement.innerHTML);
      console.log(this.t2.nativeElement.innerHTML);
      console.log(this.tt.nativeElement.innerHTML);
  }

}

运行此代码时出现以下错误

AppComponent.html:1 错误类型错误:无法读取属性 未定义的'nativeElement' 在 TestComponent.push../src/app/test/test.component.ts.TestComponent.ngAfterContentInit (test.component.ts:16) 在 callProviderLifecycles (core.js:18847) 在 callElementProvidersLifecycles (core.js:18828) 在 callLifecycleHooksChildrenFirst (core.js:18818) 在 checkAndUpdateView (core.js:19749) 在 callViewAction (core.js:19986) 在 execComponentViewsAction (core.js:19928) 在 checkAndUpdateView (core.js:19751) 在 callWithDebugContext (core.js:20639) 在 Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:20317)

我的问题是如何显示以下内容:

The following data was passed to this component:
 Test Data 1
 Test Data 2

在控制台中安全吗?

【问题讨论】:

  • 我很好奇:为什么不在服务中声明变量,然后在需要访问变量的地方导入该服务?服务非常适合共享变量,所以我想我可能没有理解您的场景。
  • @Bytech 我正在尝试创建一个可重用的组件,该组件独立于使用它的应用程序。使用服务来传输数据(在这种情况下)不会增加耦合吗?
  • 在 Angular 中,您可以保持服务松散而不是紧密耦合。听起来在您的情况下,服务是要走的路。看看stackoverflow.com/questions/50772612/… ...帖子的第二部分专门针对Angular。如果这一切都适合解决您的问题,请告诉我,我会将其放入官方答案中。如果没有,请告诉我们服务无法解决您的问题的细微差别。
  • @Bytech 我已经编辑了我的问题。 app.component.html 下面的代码没有正确显示,因为 Stack Overflow 实际渲染了它。
  • @Bytech 我的问题实际上是这样的:是否有可能以角度将子组件的选择器标签中包含的内容检索到子组件中的变量中。

标签: angular


【解决方案1】:

使用@ContentChild() 而不是@ViewChildren(),这里的链接很好地解释了这两个装饰器之间的区别:What's the difference between @ViewChild and @ContentChild?

【讨论】:

  • 请提供更全面的解释,说明为什么 OP 应该使用 ContentChild 而不是 ViewChildren,因为它也可能对其他搜索类似问题的人有用。毫无疑问,这样做也将有助于提升自己对社区有帮助的声誉。
  • @Ako Javakhishvili 尝试使用 @ContentChild() 但我收到了类似的错误。
猜你喜欢
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-19
  • 2012-12-04
  • 2019-03-23
  • 2019-02-23
相关资源
最近更新 更多