ng-content
- 使用
外部引用某组件的时候
在引用的时候会做一些处理(比如添加一个button or label),添加的元素位置和样式根据ng-content投射
demo.compent.html
<div class="demo"><p>demo title</p><div style="background-color:red"><ng-content></ng-content></div></div>
在任何时候调用时:
<app-demo><div>我是外部元素,位置和样式由ng-content决定</div></app-demo>
效果
- select 放入标签名div或者class名 表示只会放入div标签或者class名相同的标签
- 怎么获取ng-content外部的控件——contentChild、contentChildren(类似ViewChild、ViewChildren)
注意:a. 通过#自定义标签名调用 b. 要在AfterContentInit里面调用才能生效
<!--映射DemoComponent的外部组件:调用DemoComponent的地方 --><app-test-question><span #select_class>我是外部元素,位置和样式由ng-content决定</span></app-test-question>
import { Component, ContentChild, AfterContentInit } from '@angular/core';export class DemoComponent implements AfterContentInit {@ContentChild('select_class', { static: false })contentChild: any;ngAfterContentInit() {console.log(this.contentChild); // 输出结果 ElementRef {nativeElement: span}}}}
ng-container
逻辑容器,对DOM节点进行分组,但不是DOM的节点,将渲染为HTML的comment元素
angular定义的一个tag,调试的时候没有出现——不占用布局
所以在某些时候(需要用到ngif或者ngfor的时候)可以利用起来
ng-template
语法糖结构,最终转化为ng-template或者template
单独使用是不生效的,要借助其他结构指令比如ngIf、ngfor、#name
?怎么通过#name来显示ng-template
<ng-template [ngIf]="true"><p> ngIf with a ng-template.</p></ng-template><ng-template #tpl>Hello, ng-template!</ng-template>
通过TemplateRef、ViewContainerRef获取ng-template的组件,
TemplateRef是ng-template对应的类型
ViewContainerRef用来操作DOM元素的
import { Component, AfterViewInit, ViewChild, ViewContainerRef, TemplateRef } from '@angular/core';@Component({selector: 'app-demo',template: `<ng-template #tpl>Hello, ng-template!</ng-template>`,})export class DemoComponent implements AfterViewInit {@ViewChild('tpl', { static: false })tpl: TemplateRef<any>;constructor(private vcRef: ViewContainerRef) { }ngAfterViewInit() {this.vcRef.createEmbeddedView(this.tpl);}}
