Angular class binding的一个例子

117 阅读1分钟
<h2>HEROES</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes$ | async"
    [class.selected]="hero.id === selectedId">
    <a [routerLink]="['/hero', hero.id]">
      <span class="badge">{{ hero.id }}</span>{{ hero.name }}
    </a>
  </li>
</ul>

<button routerLink="/sidekicks">Go to sidekicks</button>

如果逻辑表达式hero.id === selectedId的值为true,则为li标签加上selected的class,否则移除。

在这里插入图片描述

在进入hero list UI时,从ActivatedRoute.paramMap中获取到浏览器地址栏里的hero参数,填充到selectedId去:

export class HeroListComponent implements OnInit {
  heroes$: Observable<Hero[]>;
  selectedId: number;

  constructor(
    private service: HeroService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.heroes$ = this.route.paramMap.pipe(
      switchMap(params => {
        // (+) before `params.get()` turns the string into a number
        this.selectedId = +params.get('id');
        return this.service.getHeroes();
      })
    );
  }
}

The ActivatedRoute.paramMap property is an Observable map of route parameters. The paramMap emits a new map of values that includes id when the user navigates to the component. In ngOnInit() you subscribe to those values, set the selectedId, and get the heroes.

ActivatedRoute.paramMap属性是一个被Observable包裹过的map类型,包含了路由参数。