Home javascript Angular Active Class NGFOR

Angular Active Class NGFOR




I have an array that consists of objects, I add this array to HTML using * NGFOR and process an event click to add an active class when you click Add an Active Class.

@ directive ({
 Selector: '[Apphome]'
 @Hostbinding ('class.Active') isactive = false;
 @Hostlistener ('click') onClick () {
  this.isactive = true;


& lt; li (click) = "show (idx)" class = "week-li" * ngfor = " Let WD of Weekdays; let idx = index "& gt;
        & lt; p class = "week-title" apphome & gt; {{wd.titlename}} & lt; / p & gt;
      & lt; / li & gt;
    & lt; / ul & gt;

everything works fine, click adds the expected class, but when I click on the second element, the previous active class is not deleted, how can it be implemented only with Angular, without Angular JS

Answer 1, Authority 100%

If you do not use the directive, you can do this:

& lt; div * ngfor = "let Item of Array; Let Index = Index" (click) = "ActiveIndex = index "
 [NGCLASS] = "{Active: ActiveIndex === Index}" & gt;
& lt; / div & gt;

At the same time Index and ActiveIndex it is not necessary to declare in the component, and you can leave them as variables template.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions