为什么在此示例中未定义ng-content?

时间:2018-08-06 17:22:06

标签: angular6

我对ng-content的理解是组件的开始和结束标签中的内容。

因此,如果我有一个带有选择器my-app的组件,则可以按以下方式使用它:

<my-app>
  <h1 #loading>
    loading angular app
  </h1></my-app>

然后ng-content

<h1 #loading>
        loading angular app
      </h1>

如果我理解正确,为什么在此示例中将ng-content打印为undefined

import { Component,ViewChild, ViewChildren, ContentChild,QueryList,ElementRef,Renderer2,OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular';

  @ContentChild("loading") loadingContent;

  constructor(private renderer:Renderer2, hostElementRef:ElementRef){
  }

  ngAfterContentInit(){
    console.log("loading message was ",this.loadingContent)
  }

}

组件的html是

<hello name="{{ name }}"></hello>
<p>
  I am a static component
</p>
<p #pref>
I am another para but I have an id (template reference variable) #pref. I got my blue color using ViewChild and Renderer2
</p>
<p>
  All paragraphs are small-caps because using ViewChildren and Renderer2, the style was set to bold
  </p>

使用my-app的index.html是

<my-app>
  <h1 #loading>
    loading angular app
  </h1></my-app>

在控制台中,我看到消息loading message was undefined

0 个答案:

没有答案