Angular 5:从组件生成DIV而不是新标签

问题描述 投票:1回答:3

我想知道在路由器插座中插入组件时是否有办法告诉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中呈现给这个:

<router-outlet></router-outlet>
<app-fwc-vpn-main class="ng-star-inserted"> ... </app-fwc-vpn-main>

我需要的是生成一个带有一些添加类的div,所以最终结果将是这样的:

<router-outlet></router-outlet>
<div app-fwc-vpn-main class="grid-y medium-grid-frame"> ... </div>

注意:我需要添加grid-ymedium-grid-frame类,以便应用程序具有正确的布局。这是我想要更改此div的插入标记的主要原因。

提前致谢,

angular typescript
3个回答
3
投票

在角度selector may be declared作为以下之一:

  • element-name:按元素名称选择。
  • .class:按类名选择。
  • [attribute]:按属性名称选择。
  • [attribute=value]:按属性名称和值选择。
  • :not(sub_selector):仅在元素与sub_selector不匹配时选择。
  • selector1, selector2:如果selector1selector2匹配,请选择。

因此,当angular编译组件/指令元数据时,它使用CssSelector解析选择器并保留所有解析的数据,如:

[
  {
    "element": null,
    "classNames": [
      "grid-y",
      "medium-grid-frame"
    ],
    "attrs": [
      "app-fwc-vpn-main",
      ""
    ],
    "notSelectors": []
  }
]

Angular路由器动态创建组件,因此每个路由组件都将具有Host视图。对于主机视图角度编译器prepares模板基于从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}>`;
 }

https://github.com/angular/angular/blob/c8a1a14b87e5907458e8e87021e47f9796cb3257/packages/compiler/src/selector.ts#L91-L105

之后主机模板将是:

<div class="grid-y medium-grid-frame" app-fwc-vpn-main></div>

所以以下内容适合您:

selector: '[app-fwc-vpn-main].grid-y.medium-grid-frame',

Example


1
投票

然后从以下位置更改selector

selector: 'app-fwc-vpn-main',

selector: '[app-fwc-vpn-main]',

然后你可以像<div app-fwc-vpn-main></div>一样使用它

@Component选择器 - 用于在模板中标识此组件的css选择器

所以你可以使用任何css选择器

.app-fwc-vpn-main // <div class='app-fwc-vpn-main'></div>
#app-fwc-vpn-main // <div id='app-fwc-vpn-main'></div>

欲了解更多详情,请阅读:Component


-1
投票

创建指令而不是组件

<div app-fwc-vpn-main class="grid-y medium-grid-frame"> ... </div>

在这种情况下,app-fwc-vpn-main是指令。您可以创建指令并渲染所需的模板,而不是创建组件。

© www.soinside.com 2019 - 2024. All rights reserved.