Angular. Built-in directives. Dynamic element attributes

Home » Tutorials » JavaScript » Angular. Built-in directives. Dynamic element attributes
In this video we’ll talk about several built-in Angular directives – ngStyle, ngClass, ngSwitchCase, ng-template
Also we’ll discuss local templates inside ngFor element template. Especially I notice about importance of trackBy. This param increase Angular apps performance  while rendering large data collections.
Code lesson (component class)
import { Component } from '@angular/core';
import { UserService } from './services/user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user: any;
  myClass = 'myClass';
  color: 'red' | 'green' = 'red';

  constructor(private _userService: UserService) {
  }

  getUser() {
    this.user = this._userService.getUser();
  }

  changeColor() {
    this.user.login = 'new login';
    this.color = this.color === 'red' ? 'green' : 'red';
  }

  trackRole(index, item) {
    console.log(index, item);
  }
}
Code lesson (component template)
<p [attr.class]="'myClass'" [style.fontSize]="'20px'">User info</p>
<p [attr.class]="myClass" [style.fontSize]="'20px'">User info</p>

<button (click)="getUser()">Get user</button>

<div *ngIf="user; else userNotFound">
  <span (click)="changeColor()" [ngStyle]="{'color': color}">{{user.login}}</span>
  <p [ngClass]="{'oneRole': user.roles.length === 1, 'twoRoles': user.roles.length === 2}" [ngSwitch]="user.roles.length">
    <ng-template ngSwitchCase="1">1 user role</ng-template>
    <ng-template ngSwitchCase="2">1 user role</ng-template>
    <ng-template ngSwitchDefault>no user roles</ng-template>
  </p>


  <ul>
    <li *ngFor="let role of user.roles; index as i; first as isFirst; last as isLast; trackBy: trackRole">
      {{i}} {{role}} {{isFirst}} {{isLast}}
    </li>
  </ul>

</div>

<ng-template [ngIf]="!user">
  User not found
</ng-template>

<ng-template #userNotFound>
  <div>User not found!</div>
</ng-template>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Подписаться на рассылку

Будьте в курсе - получайте последние статьи на свой email

Ваша подписка успешно оформлена

Pin It on Pinterest

Share This