ng-template、ng-container、ng-content 的用法

ng-container:此标签不渲染成DOM;默认显示标签内部内容,也可以使用结构型指令(ngIf、ngFor...)

官网详细介绍:https://angular.cn/guide/structural-directives

eg:代码块


  

Hello World !!!

网页渲染结果

Hello World !!!

 

ng-content:父组件调用子组件时,将父组件内容投射到子组件指定位置(子组件中 ng-content 所在位置);类似 VUE 中的插槽。分为默认投射,具名投射。

1)默认投射 - 子组件中只有一个 ng-content 时:eg

父组件中引入子组件


  

- parent component content !!! -

子组件

child component content - begin

child component content - end

显示效果

child component content - begin

- parent component content !!! -

child component content - end

2)具名投射 - 子组件有多个 ng-content,需要指定名字进行指定位置投射:eg

父组件内容 


  
header - parent component content !!! -
id selector - parent component content !!! -
name - parent component content !!! -

 子组件内容

child component content

child component content

child component content

使用 select 属性,支持 CSS 选择器

 

ng-template:模板元素,默认情况内部元素不可见。使用方法:

方法一:使用 ngIf 属性,值为 true 显示内容


  

Hello World !!!

扩展:以下代码会转换为以上代码显示

Hello World !!!

方法二: 使用 ViewContainerRef,TemplateRef,ViewChild:eg

组件 HTML



  

调用的模板数据:{ { name1 }} -- { { foo }}

组件 TS,以上代码默认不起任何作用,不会渲染 DOM 

Angular8 必填 {static: boolean} 属性
true:变更检测之前解析查询结果;反之

// 获取指定模板(myTpl)引用 tpl
@ViewChild('myTpl', {static: true}) tpl: TemplateRef;
constructor(
  private viewContainer: ViewContainerRef
) { }
// $implicit:默认输入变量取值
ngOnInit() {
  this.viewContainer.createEmbeddedView(this.tpl, { $implicit: "Hello", name: 'World' });
}

效果,显示模板内容

方法三:使用 ngTemplateOutlet 结构型指令:eg

组件 HTML


调用的模板数据:{ { name1 }} -- { { foo }}

组件 TS

context = { $implicit: "World", name: 'liyq' };

可以将指定模板插入到指定位置,TS 中只需要定义数据

方法四:使用自定义结构型指令,和 ngIf 类似:eg

1)ng g d unless 创建一个名为 unless 的结构型指令

unless.directive.ts

import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';

@Directive({
  selector: '[appUnless]'
})
export class UnlessDirective {

  constructor(
    private templateRef: TemplateRef,
    private viewContainer: ViewContainerRef
  ) { }

  // 必须使用 set 方法
  @Input() set appUnless(condition: boolean) {
    if(!condition) {
      // 下面是渲染模板数据的核心
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }

}

组件 HTML

// 模板渲染结果和 condition 的 Boolean 值没有关系,主要的作用为作为参数传递给自定义的结构指令

  

使用结构型指令调用模板

 

你可能感兴趣的:(Angular,angular)