Angular 5: 从组件生成DIV而不是新标签
Angular 5: 从组件生成DIV而不是新标签
我想知道是否有一种方法,告诉Angular在插入组件到路由出口时生成DIV而不是新标签。目前,我有这个组件代码:
import { Component, OnInit, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-fwc-vpn-main', templateUrl: './fwc-vpn-main.component.html', styleUrls: ['./fwc-vpn-main.component.css'], encapsulation: ViewEncapsulation.None }) export class FwcVpnMainComponent implements OnInit { numbers = new Array(35); constructor() { } ngOnInit() { } }
在最终的HTML中呈现为:
...
我需要生成一个带有一些添加类的div,以便最终结果类似于:
...
注意:我需要添加grid-y
和medium-grid-frame
类以确保应用程序具有正确的布局。这是我想要更改此div的插入标记的主要原因。
预先感谢您的帮助,
admin 更改状态以发布 2023年5月23日
然后将 selector
从 :
selector: 'app-fwc-vpn-main',
改为
selector: '[app-fwc-vpn-main]',
然后您可以像这样使用它
@Component selector - 标识此组件在模板中使用的 CSS 选择器
因此,您可以使用任何 CSS 选择器,例如
.app-fwc-vpn-main // #app-fwc-vpn-main //
想了解更多详细信息,请阅读:Component
在Angular中,选择器可以声明为以下之一:element-name
:按元素名称选择。 .class
:按类名选择。 [attribute]
:按属性名称选择。 [attribute=value]
:按属性名称和值选择。 :not(sub_selector)
:仅选择不匹配sub_selector
的元素。 selector1,selector2
:如果selector1
或selector2
匹配,则选择。
因此,当Angular编译Component / Directive元数据时,它使用CssSelector解析选择器,并保存所有解析的数据,例如:
[ { "element": null, "classNames": [ "grid-y", "medium-grid-frame" ], "attrs": [ "app-fwc-vpn-main", "" ], "notSelectors": [] } ]
Angular路由器动态创建组件,因此我们的每个路由组件都将具有宿主视图。对于宿主视图,Angular编译器根据从CssSelector收到的元数据准备模板:
/** Gets a template string for an element that matches the selector. */ getMatchingElementTemplate(): string { const tagName = this.element || 'div'; const classAttr = this.classNames.length > 0 ? ` class="${this.classNames.join(' ')}"` : ''; let attrs = ''; for (let i = 0; i < this.attrs.length; i += 2) { const attrName = this.attrs[i]; const attrValue = this.attrs[i + 1] !== '' ? `="${this.attrs[i + 1]}"` : ''; attrs += ` ${attrName}${attrValue}`; } return getHtmlTagDefinition(tagName).isVoid ? `<${tagName}${classAttr}${attrs}/>` : `<${tagName}${classAttr}${attrs}>${tagName}>`; }
之后,主机模板将为:
因此,以下内容应适用于您:
selector: '[app-fwc-vpn-main].grid-y.medium-grid-frame',