[英]How to define if component nested to itself in Angular 6?
I try to create custom Angular component for navigation menu. 我尝试为导航菜单创建自定义角度组件。 This menu can be nested, so it is 2nd level menu. 此菜单可以嵌套,因此它是第二级菜单。 Here is how it looks: 以下是它的外观:
app.component.html app.component.html
<nav-menu>
<nav-menu-item>Section 1</nav-menu-item>
<nav-menu-item>Section 2
<nav-menu>
<nav-menu-item>Subsection 2.1</nav-menu-item>
<nav-menu-item>Subsection 2.2</nav-menu-item>
<nav-menu-item>Subsection 2.3</nav-menu-item>
</nav-menu>
</nav-menu-item>
<nav-menu-item>Section 3</nav-menu-item>
</nav-menu>
I have created two components. 我创建了两个组件。
menu.component.ts menu.component.ts
import { Component, HostBinding } from '@angular/core';
@Component({
selector: 'nav-menu',
template: '<ng-content select="nav-menu-item"></ng-content>',
styleUrls: ['./menu.component.css']
})
export class MenuComponent {
@HostBinding('class') class = 'nav-menu';
}
menu-item.component.ts 菜单item.component.ts
import { Component, HostBinding } from '@angular/core';
@Component({
selector: 'nav-menu-item',
template: '<ng-content></ng-content>',
styleUrls: ['./menu-item.component.css']
})
export class MenuItemComponent {
@HostBinding('class') class = 'nav-menu-item';
}
The problem is that the sub-menu must have different styles. 问题是子菜单必须具有不同的样式。 So I have to differ if menu item is nested (2nd level) or not. 所以如果菜单项是嵌套的(第二级),我必须有所不同。 I can fix this problem in CSS with such selector .nav-item .nav-item {}
, but it would be better to have different CSS classes for 1st and 2nd level of menu item. 我可以使用这样的选择器.nav-item .nav-item {}
在CSS中解决这个问题,但是对于第一级和第二级菜单项,最好有不同的CSS类。
How to define if component nested to itself? 如何定义组件是否嵌套到自身?
You can piece through with >>> 你可以用>>>来完成
:host >>> nav-menu-item
Should allow you to style the child 应该让你为孩子设计风格
https://stackblitz.com/edit/angular-nested-nav-menu-3v4iat https://stackblitz.com/edit/angular-nested-nav-menu-3v4iat
I found the solution with dependency injection parameters @Optional
and @SkipSelf
. 我找到了依赖注入参数@Optional
和@SkipSelf
的解决方案。 If the menu has the same menu among the ancestors, then this menu is nested. 如果菜单在祖先中具有相同的菜单,则此菜单是嵌套的。 Same for menu items. 菜单项也一样。
constructor(@Optional() @SkipSelf() parentMenu: MenuComponent) {
if (parentMenu) {
this.class = 'nav-submenu';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.