ng-content

  1. 使用

外部引用某组件的时候
在引用的时候会做一些处理(比如添加一个button or label),添加的元素位置和样式根据ng-content投射
demo.compent.html

  1. <div class="demo">
  2. <p>demo title</p>
  3. <div style="background-color:red">
  4. <ng-content></ng-content>
  5. </div>
  6. </div>

在任何时候调用时:

  1. <app-demo>
  2. <div>我是外部元素,位置和样式由ng-content决定</div>
  3. </app-demo>

效果
image.png

  1. select 放入标签名div或者class名 表示只会放入div标签或者class名相同的标签

  1. 怎么获取ng-content外部的控件——contentChild、contentChildren(类似ViewChild、ViewChildren)

注意:a. 通过#自定义标签名调用 b. 要在AfterContentInit里面调用才能生效

  1. <!--映射DemoComponent的外部组件:调用DemoComponent的地方 -->
  2. <app-test-question>
  3. <span #select_class>我是外部元素,位置和样式由ng-content决定</span>
  4. </app-test-question>
  1. import { Component, ContentChild, AfterContentInit } from '@angular/core';
  2. export class DemoComponent implements AfterContentInit {
  3. @ContentChild('select_class', { static: false })
  4. contentChild: any;
  5. ngAfterContentInit() {
  6. console.log(this.contentChild); // 输出结果 ElementRef {nativeElement: span}
  7. }
  8. }
  9. }

ng-container

逻辑容器,对DOM节点进行分组,但不是DOM的节点,将渲染为HTML的comment元素
angular定义的一个tag,调试的时候没有出现——不占用布局
所以在某些时候(需要用到ngif或者ngfor的时候)可以利用起来

ng-template

语法糖结构,最终转化为ng-template或者template
单独使用是不生效的,要借助其他结构指令比如ngIf、ngfor、#name
?怎么通过#name来显示ng-template

  1. <ng-template [ngIf]="true">
  2. <p> ngIf with a ng-template.</p>
  3. </ng-template>
  4. <ng-template #tpl>
  5. Hello, ng-template!
  6. </ng-template>

通过TemplateRef、ViewContainerRef获取ng-template的组件,
TemplateRef是ng-template对应的类型
ViewContainerRef用来操作DOM元素的

  1. import { Component, AfterViewInit, ViewChild, ViewContainerRef, TemplateRef } from '@angular/core';
  2. @Component({
  3. selector: 'app-demo',
  4. template: `
  5. <ng-template #tpl>
  6. Hello, ng-template!
  7. </ng-template>
  8. `,
  9. })
  10. export class DemoComponent implements AfterViewInit {
  11. @ViewChild('tpl', { static: false })
  12. tpl: TemplateRef<any>;
  13. constructor(private vcRef: ViewContainerRef) { }
  14. ngAfterViewInit() {
  15. this.vcRef.createEmbeddedView(this.tpl);
  16. }
  17. }