美文网首页
Angular 内容投影 content projection

Angular 内容投影 content projection

作者: _扫地僧_ | 来源:发表于2022-03-17 09:23 被阅读0次

    问题描述

    我定义了一个能够允许消费者 Component 将其自定义内容通过 content projection 投射进来的 Component:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-zippy-basic',
      template: `
        Default:
        <ng-content></ng-content>
    
        Question:
        <ng-content select="[question]"></ng-content>
      `
    })
    export class ZippyBasicComponent {}
    

    其中包含 defaultquestion 两个区域。

    对于 question 区域而言,只有在消费 Component 提供的内容,满足第 10 行指定的选择器时,该内容才能被投影到 app-zippy-basic 内部。

    我的消费代码如下:

    <app-zippy-basic>
        <p #question>
            带了问号的 p 节点
          </p>
          <p>普通 p 节点</p>
    </app-zippy-basic>
    

    我期望的结果:

    • 普通 p 节点,出现在 default 区域;
    • 带了问号的 p 节点,出现在 question 区域。

    实际测试结果:question 区域为空。

    问题分析

    根据 Angular 官网的定义,select="[question]" 的语法含义是,将消费 Component 中具有 questionattribute 的 dom 节点,投射到 app-zippy-basic 中。因此,第 23 行中的 # 应该去掉,这样才能产生一个具有 question 属性的 p 节点:

    去掉之后,p 节点果然按照我们期望的那样,显示在 default 区域了:

    我们再来通过单步调试的方式,找到带有 question 属性的 p 节点是如何被选择以及投射的。

    Angular 框架内部维护了一个叫做 LViewLogic View 的数据结构,这是一个数组:

    LView 的内容:

    其中索引为 21 的数组元素,rawSlotValue,存放的就是需要被投影到 question 区域,带有 question 属性的 p 节点。

    总结

    如果组件包含一个没有 select 属性的 ng-content 元素,则该实例会接收与任何其他 ng-content 元素都不匹配的所有投影组件。

    逻辑视图 (LView) 表示模板 (TView) 的实例。 我们使用逻辑这个词来强调开发人员如何从逻辑角度看待应用程序。 ParentComponent 包含一个 ChildComponent。 从逻辑的角度来看,我们认为 ParentComponent 包含 ChildComponent,因此称为逻辑。 逻辑一词与渲染树的最终概念形成对比。

    相关文章

      网友评论

          本文标题:Angular 内容投影 content projection

          本文链接:https://www.haomeiwen.com/subject/mxeerrtx.html