【发布时间】:2019-11-16 02:40:54
【问题描述】:
当某个类存在于某个父组件/元素中时,我希望 Angular 组件的内容发生变化。与 :host-context() CSS 选择器非常相似,但在 TypeScript 组件代码中。
使用:host-context(.the-class),我可以控制组件中元素的可见性,但这只会修改组件的样式。我也想修改行为。
我还尝试了带有$(this.element.nativeElement).parents().hasClass("the-class"); 的JQuery 路由。这工作得相当好,但我更喜欢声明性/角度的方法。
@Component({
template: `
<p>{{text}}</p>
`,
styles: [`
:host-context(.the-class) p {
color: red;
}
`]
})
class MyComponent {
text: string;
/*
Change content of 'text' if 'the-class' can be found
in any of the parents here somewhere.
*/
}
那么...在不使用 JQuery 或原生 DOM 选择器的情况下,最好的“Angular 方式”是什么?我意识到这可能不是一个常见的用例,因为它会破坏组件隔离等等。但我想,既然:host-context 选择器是为了样式而存在的,那么控制器肯定也有类似的东西。
【问题讨论】:
标签: angular typescript