Angular中_ngcontent-c#是什么意思?

50

我正在学习Angular 2/4,看到带有ng生成属性的html标记: _ngcontent-c0, _ngcontent-c1...

这个c值代表什么意思?

2个回答

36

_ngcontent-c# 属性会在使用 ViewEncapsulation.Emulated 时自动添加,而这是默认的行为。Angular 使用这些属性来定位带有样式的特定元素。数字 c 是宿主组件的一种唯一标识符。例如,如果你有以下两个模板的组件:

ComponentA
<span></span>
<comp-b></comp-b>

ComponenB
<h1></h1>

Angular将会标记所有位于组件 A 内部样式的元素为“_ngcontent-c0”,并将所有位于组件 B 内部样式的元素标记为“_ngcontent-c1”:

<comp-a>
    <span _ngcontent-c0></span>
    <comp-b _ngcontent-c0>
        <h1 _ngcontent-c1></h1>
    </comp-b>
</comp-a>

那么根组件将是0,嵌套的组件将是1...n吗? - Maddy
1
我不确定我是否喜欢或需要这个“_ngcontent..”,如何关闭它? - Tom Stickel
3
@TomStickel,ViewEncapsulation.Emulated是默认模式。 它在组件装饰器描述符属性中指定。 - Max Koretskyi
1
一切都很好,但_ngcontent-c#有什么影响? - Scott
@Scott,你能澄清一下你的意思吗?我使用了#代替数字。它用于定位CSS选择器并应用封装样式。 - Max Koretskyi
显示剩余7条评论

17

您可以通过添加以下导入到您的组件来禁用它:

import {ViewEncapsulation} from '@angular/core';

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

请注意此行:

 encapsulation: ViewEncapsulation.None

不要从Angular中添加动态属性


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接