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

angular – 如何在呈现的HTML中删除额外的包装元素?

发布时间:2020-12-17 18:02:53 所属栏目:安全 来源:网络整理
导读:我3天前开始学习角度,所以我很陌生.我还使用angularJS和React开发应用程序,我想我不明白角度5组件是如何完全工作的.如果我创建一个自定义文本的自定义按钮(我不是说这应该以这种方式完成,但这是一个显示我的观点的简单示例),如下所示: app-button app-text
我3天前开始学习角度,所以我很陌生.我还使用angularJS和React开发应用程序,我想我不明白角度5组件是如何完全工作的.如果我创建一个自定义文本的自定义按钮(我不是说这应该以这种方式完成,但这是一个显示我的观点的简单示例),如下所示:

<app-button>
  <app-text>
    My Text
  </app-text>
</app-button>

渲染的DOM导致:

<app-button>
  <button>
    <app-text>
      <span>
        My Text
      </span>
    </app-text>
  </button>
</app-button>

这是不可读的,我想知道是否有办法删除这个包装元素,只是放置组件布局替换标签导致以下结构:

<button>
  <span>
    My Text
  </span>
</button>

如果没有办法删除它们你的建议是什么?谢谢!

解决方法

角度组件是带有模板的指令. According to this:

Directive configuration @Directive({ property1: value1,… })

selector: ‘.cool-button:not(a)’ Specifies a CSS selector that
identifies this directive within a template. Supported selectors
include element,[attribute],.class,and :not().

因此组件选择器也可以是属性选择器.对于您的示例,而不是写这个:

parent.component.html:

<app-button>
  <app-text>
    My Text
  </app-text>
</app-button>

写这个:

parent.component.html:

<button app-button>
    <span app-text>My Text</span>
</button>

其中:

APP-button.component.ts

...  
  selector: '[app-button]',template: `<ng-content></ng-content>
...

APP-text.component.ts

...
  selector: '[app-text]',template: `<ng-content></ng-content>`
...

这将按照您的预期呈现:

enter image description here

评论后更新:

要从按钮组件内部设置按钮样式,可以从按钮组件中分离封装.然后,您可以从按钮组件设置样式并在父组件中设置类:

button.component.ts

import { Component,ViewEncapsulation } from '@angular/core';
...    
styles: ['.button-1{background-color:red}','.button-2{background-color:blue}'],encapsulation: ViewEncapsulation.None

app.component.html

<button app-button class="button-1">
    <span app-text>My Text</span>
</button>

<button app-button class="button-2">
    <span app-text>My Text</span>
</button>

这是DEMO

(编辑:李大同)

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

    推荐文章
      热点阅读