I have a list-group defined as a list of recipe-items . I'm using the child routing in order to display a description of the item whenever the user clicks on a list element. So far the click event and the routing are working but I want to mark the clicked item as active .
recipe-list.component.html
<app-recipe-item
*ngFor="let recipeEl of recipes; let i = index"
[recipe]="recipeEl"
[routerLink]="i"
style="cursor: pointer;"
>
</app-recipe-item>
In order to do it I'm trying to use the routerLinkActive directive within my nested RecipeItemComponent
but it looks like the directive is out of scope for the nested component.
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>
What am I missing? Even using a localRef it's impossible to retrieve its value in a nested component.
RouterLinkActive
directive and its property isActive
Using the RouterLinkActive
and a local reference it's possible to pass the value of isActive
to an @Input()
property of the nested component in order to use it in its template to trigger ngClass
.
recipe-list.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
directive add special styles to actived link by subscribing to router's navigate event, see source code .
You can do the same in your app-recipe-item
component as well without using routerLinkActive directive.(code is the same)
Another way, routerLinkActive
provides an isActive
property which shows whether current routerLink is active or not. You can inject it as your component as well to retrieve its value and change to active style.
<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>
Refer demo .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.