Search code examples
javascripthtmlangularngforng-class

How to change the appearance of blocks located in ngFor?


I have an article-map component. In it, with the help of the ngFor directive, I display brief information about the articles. I call the "article-map" component in the "feed" component. The "feed" component should have three views with different "article-map" styling. For example: the first one is a sheet, the second one is two columns, etc. How do I style the article-map component for different feed views using ngClass?

I started with the following. In article-card.component.ts I set a variable to get the parameter from the link.

export class ArticleCardComponent implements OnInit {
  constructor(private route: ActivatedRoute) { }
  typeView='default';

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      console.log(params)
      this.typeView=params['viewType'];
    })
  }
}

Now I want to write a ternary expression for ngClass that will allow different style classes to be used for feed views. Tell me how to do it?


Solution

  • In your case it will be.

    <div [ngClass]="typeView ===  'default' ? 'css-class-1' : 'css-class-2'">
    

    If you want more than one condition write a function like

    html

    <div [ngClass]="getClass()">
    

    ts

    getClass() {
        switch(this.typeView) {
            case 'default':
                return 'css-class-1';
            case 'special':
                return 'css-class-2';
            default:
                return 'css-class';
        }
    }