[英]Accessing RouterLinkActive in a nested component using Angular 6
我有一个定义为食谱项目列表的列表组。 我正在使用子级路由,以便在用户单击列表元素时显示项目的描述。 到目前为止,单击事件和路由都可以正常工作,但是我想将单击的项目标记为活动 。
配方列表.component.html
<app-recipe-item
*ngFor="let recipeEl of recipes; let i = index"
[recipe]="recipeEl"
[routerLink]="i"
style="cursor: pointer;"
>
</app-recipe-item>
为了做到这一点,我试图在嵌套的RecipeItemComponent
使用routerLinkActive指令,但是该指令似乎超出了嵌套组件的范围。
recipe-item.component.html
<div class="list-group">
<a
class="list-group-item list-group-item-action d-flex justify-content-between align-items-start"
routerLinkActive="active"
>
TO BE MARKED AS ACTIVE WHEN CLICKED
</a>
</div>
我想念什么? 即使使用localRef,也无法在嵌套组件中检索其值。
RouterLinkActive
指令及其属性为isActive
使用RouterLinkActive
和本地引用,可以将isActive
的值传递给嵌套组件的@Input()
属性,以便在其模板中使用它来触发ngClass
。
配方列表.component.html
<app-recipe-item
*ngFor="let recipeEl of recipes; let i = index"
[recipe]="recipeEl"
[routerLink]="i"
routerLinkActive
#rla="routerLinkActive"
[currentlySelected]="rla.isActive"
style="cursor: pointer;"
>
</app-recipe-item>
recipe-item.component.ts
@Component({
selector: 'app-recipe-item',
templateUrl: './recipe-item.component.html',
styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {
@Input() recipe: Recipe;
@Input() currentlySelected: boolean;
recipe-item.component.html
...
<a [ngClass]="{active: currentlySelected}">
...
routerLinkActive
指令通过订阅路由器的Navigation事件来向活动链接添加特殊样式,请参见源代码 。
您也可以在app-recipe-item
组件中执行相同的操作,而无需使用routerLinkActive指令。(代码相同)
另一种方法, routerLinkActive
提供了isActive
属性,该属性显示当前的routerLink是否处于活动状态。 您也可以将其作为组件注入,以获取其值并更改为活动样式。
<app-recipe-item
*ngFor="let recipeEl of recipes;
let i = index" [recipe]="recipeEl"
[routerLink]="i" style="cursor: pointer;"
routerLinkActive
>
</app-recipe-item>
constructor(
@Inject(RouterLinkActive) private activeRouter: RouterLinkActive // inject
) { }
<a class="list-group-item list-group-item-action d-flex justify-content-between align-items-start"
[ngClass]="{active: activeRouter.isActive}"
>
TO BE MARKED AS ACTIVE WHEN CLICKED
</a>
请参阅demo 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.