加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

【Angular】组件内容嵌入ng-content

发布时间:2020-12-17 08:31:49 所属栏目:安全 来源:网络整理
导读:组件的内容嵌入:在组件中嵌入模板代码,提高组件的可复用性。很好得扩充组件的功能,方便代码的服用。典型的例子就是:模态对话框或导航栏的使用,通常模态对话框和导航栏的样式是一样的,这是如果有一个模板,我们只负责往里面填充数据,是不是就方便使用

组件的内容嵌入:在组件中嵌入模板代码,提高组件的可复用性。很好得扩充组件的功能,方便代码的服用。典型的例子就是:模态对话框或导航栏的使用,通常模态对话框和导航栏的样式是一样的,这是如果有一个模板,我们只负责往里面填充数据,是不是就方便使用多了,组件内容嵌入就是解决此类问题的。下面举例说明:

文件目录如下:

// example-content.component.ts 
import { Component,OnInit } from '@angular/core';

@Component({
  selector: 'example-content',templateUrl: './example-content.component.html',styleUrls: ['./example-content.component.css'],})
export class ExampleContentComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

设置模板

<!--example-content.component.html -->
<div>
    <table >
      <body class="tbody">
        <tr >
          <td class="header tborder">
              <ng-content select="header"></ng-content>
          </td>
        </tr>

        <tr>
            <td class="body tborder">
                <ng-content select=".body"></ng-content>                         
            </td>
          </tr>

          <tr>
              <td class="footer tborder">
                  <ng-content select="[name=footer]"></ng-content>
              </td>
            </tr>
      </body>

    </table>   
</div>
  • 标签:用来渲染组件嵌入的内容
  • 属性select=“header”:select是个选择器,类似于css选择器,它匹配<example-content>标签之间的第一个header**标签**,并把内容填充到ng-content中
  • select=”.body”:使用了类选择器来指定ng-content,“.body”是<example-content>标签的一个class名字
  • select=”[name=footer]”:使用了属性选择器来指定ng-content,“footer”是<example-content>标签的一个name名字
    注意三者select的写法

模板样式

// example-content.component.css 
.tbody {
    border: 1px solid;
    border-collapse: collapse;
}
.tborder{
    border: 1px solid ;

}
.header{
    background-color: rgb(189,187,187);
}
.body {
    height: 100px;   
    width: 200px;  
}
.footer{
    background-color:rgb(189,187);
}

为模板添加内容

<!--app.component.html-->
<example-content >
  <header>联系人</header>
  <div class="body">
      李四:18766892869
  </div>
  <div name="footer">
      查看详情请点击联系人
  </div>
</example-content>
  • 标签必须是模板中selector的指定标签
  • <example-content >标签之间的内容被填充到了ng-content中,

运行后得到如图

如果别的程序想用这个样式,只需改变一下内容:只需改动引用该模板样式的模板,如

<!--app.component.html-->
<example-content >
  <header>商店</header>
  <div class="body">
      水果类
  </div>
  <div name="footer">
      由霜有限公司提供
  </div>
</example-content>

运行结果如下

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读