将在组件内部投射的内容检索到变量

时间:2019-01-03 10:18:11

标签: angular

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

我尝试使用@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错误TypeError:无法读取属性   未定义的“ 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 [作为checkAndUpdateView](core.js:20317)

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

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

在控制台中安全吗?

1 个答案:

答案 0 :(得分:2)

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