Angular 4 CSS 在 document.createElement()

Angular 4 CSS on document.createElement()

我尝试在 Angular 4.

中动态创建元素

TS

const bookmark = document.createElement('a');
bookmark.className = 'bookmark';

SCSS

.bookmark {
  display: block;
  background: white;
  color: #999;
  padding: 20px;
  transition: 0.3s ease all;
  border-bottom: 1px solid #DDD;
}

但是,该样式不适用于 SASS 文件中的元素。如果我直接在JS文件中添加样式,就可以了:

const bookmark = document.createElement('a');
bookmark.className = 'bookmark';

bookmark.style.display = 'block';
bookmark.style.background = 'white';
bookmark.style.color = '#999';
bookmark.style.padding = '20px';
bookmark.style.transition = '0.3s ease all';
bookmark.style.borderBottom = '1px solid #DDD';

如果我直接在 HTML 文件中创建元素,它会自动获得一个 _ngcontent-c1 属性,而在 TS 中创建的元素缺少此属性(如果我在 Chrome Developer Tools - Element 面板中手动设置,它从 SCSS 获取样式。

<div class="bookmarks-list">
  <a class="bookmark">
    I am the bookmark
  </a>
</div>

我的问题是,如何将 SASS 文件中的 .bookmark class 样式应用到 TS 中创建的书签元素?

你没有分享完整的代码,但可能是你在哪里创建元素的问题,如果它在一个组件中,它可能不会到达你的 css 由于封装,尝试使用一些东西如下所示:

@Component({
// ...
encapsulation: ViewEncapsulation.None, //<<<<< this one!
styles: [
  // ...
]
})
export class HelloComponent {
// ...
}

有关详细信息,请访问下面的 link: https://angular.io/docs/ts/latest/guide/component-styles.html#!#view-encapsulation