![](/img/trans.png)
[英]How do I not render ViewChild element but access it in the parent component instead?
[英]How do I detect class of parent element/component
我希望当父组件/元素之一中存在某个类时,更改Angular组件的内容。 与:host-context()
CSS选择器非常相似,但是在TypeScript组件代码中。
使用:host-context(.the-class)
,我可以控制组件中元素的可见性,但这只会修改组件的样式。 我也想修改行为。
我也尝试过使用$(this.element.nativeElement).parents().hasClass("the-class");
进行JQuery路由$(this.element.nativeElement).parents().hasClass("the-class");
。 这可以很好地工作,但是我更喜欢声明性/角度的方法。
@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选择器的情况下,实现这种“角度方式”的最佳方法是什么? 我意识到这可能不是一个常见的用例,因为它会破坏组件的隔离等等。 但是我认为,因为:host-context
选择器用于样式设置,所以控制器必须有类似的东西。
也许您可以在子组件中阅读父样式表,那么很容易找到该类。
为了Exp;
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss', '../parent.component.scss']
})
此处的样式URL angular允许添加多个样式表,因此可以在此处添加父样式,然后可以使用js方法查找类document.getElementsByClassName(names);
;。
您可以在Angular中很好地做到这一点。
首先,您可以声明一个变量来获取相关的类,例如
const classname = document.querySelector('the-class') as HTMLElement;
let container = classname.parentNode;
console.log(container) // You can console log this to see the parent class for yourself
这样一来,您应该可以做任何您想做的事情。
假设您的类是输入或与之相关的任何元素,您也可以在Angular组件中进行类似的操作
const classname = document.querySelector('the-class') as HTMLElement;
classname.onClick = () => {
let container = classname.parentNode;
console.log(container) // You can console log this to see the parent class
let container = classname.parentNode;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.