angular内容投影详解

单内容投影

利用ng-content来实现


标题

this is content

多内容投影

利用ng-content来实现


Herder Title

Body Title

Default Title

Footer Title

this is default01
this is header
this is default02
this is body
this is default03
this is footer
this is default04

有条件的内容投影-ng-template, ng-container, directive 等来配合实现

单个条件的内容投影

eg: 假设现在有一个人员列表,当某个人的money大于200的时候,额外添加组件中模板定义的内容

定义一个 appChildRef 指令来配合 ng-template 获取模板

import { Directive, TemplateRef } from '@angular/core';
@Directive({
  selector: '[appChildRef]'
})
export class ChildRefDirective {
  constructor(public templateRef: TemplateRef) { }
}

app-persons - html

Name: {{ person.name }}
Money: {{ person.money }}

app-persons - ts

import { Component, ContentChild, OnInit } from '@angular/core';
import { ChildRefDirective } from '../../../../directives/child-ref.directive';
@Component({
  selector: 'app-persons',
  templateUrl: './persons.component.html',
  styleUrls: ['./persons.component.scss']
})
export class PersonsComponent implements OnInit {
  persons: { name: string; money: number; }[] = [
    { name: '杰克', money: 120 },
    { name: '李莉', money: 210 },
    { name: '张三', money: 170 },
  ];
  @ContentChild(ChildRefDirective, { static: true }) childRef!: ChildRefDirective;
  constructor() { }
  ngOnInit(): void { }
}

使用


  
    
this is child ref content

效果图

angular内容投影详解_第1张图片

多个条件内容投影

eg: 现在希望通过 persons 数据中的字段进行绑定内嵌的模板来显示

appChildRef 调整

import { Directive, Input, TemplateRef } from '@angular/core';
@Directive({
  selector: '[appChildRef]'
})
export class ChildRefDirective {
  // 接受定义模板名称-通过这个名称和 persons 中的render字段对应进行显示对应的模板内容
  @Input() appChildRef!: string;
  constructor(public templateRef: TemplateRef) { }
}

app-persons - html

Name: {{ person.name }}
Money: {{ person.money }}

app-persons - ts

import { Component, ContentChild, ContentChildren, OnInit, QueryList } from '@angular/core';
import { ChildRefDirective } from '../../../../directives/child-ref.directive';
@Component({
  selector: 'app-form-unit',
  templateUrl: './form-unit.component.html',
  styleUrls: ['./form-unit.component.scss']
})
export class FormUnitComponent implements OnInit {
  persons: { name: string; money: number; render?: string; }[] = [
    { name: '杰克', money: 120, render: 'temp1' },
    { name: '李莉', money: 210, render: 'temp2' },
    { name: '张三', money: 170, render: 'temp3' },
  ];
  // @ContentChild(ChildRefDirective, { static: true }) childRef!: ChildRefDirective;
  @ContentChildren(ChildRefDirective) childrenRef!: QueryList;
  get tempRefs() {
    const aObj: any = {};
    this.childrenRef.forEach(template => {
      const key: string = template.appChildRef;
      aObj[key] = template;
    })
    return aObj;
  }
  constructor() { }
  ngOnInit(): void { }
}

使用


  
    
{{index}}-{{person.name}}: this is temp1
{{index}}-{{person.name}}: this is temp2
{{index}}-{{person.name}}: this is temp3

效果图

angular内容投影详解_第2张图片

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

你可能感兴趣的:(angular内容投影详解)