Angular Note 3 --- ngFor/ ngIf/ ngSwitch

111 阅读1分钟

1. For loop (*ngFor)

app.component.ts

public items = ["abc", "bcd", "dfv"];

public items: string[] = ["abc", "dbc"];

public items: Array<string> = ["abc", "bcd"];

// All of those above two are good


public usersArr: UserInfo[] = [    {      username: "John",      age: 13    },    {      username: "Kevin",      age: 23    }]

app.component.html

<ul>
  <li *ngFor="let item of items">
     {{item}}
  </li>
</ul>

<ol>    <li *ngFor="let item of usersArr">        {{item.username}}: {{item.age}}    </li></ol>

<ol>

// get the index of every item in the array<ol>    <li *ngFor="let item of usersArr; let key=index">        {{key}} --- {{item.username}}: {{item.age}}    </li></ol>

2. img property binding

app.component.ts

public picUrl = "...";

app.component.html

<h1>Show images here</h1>
<img [src]="picUrl" alt="logo" />

3. if --- *ngIf 

app.component.html

<ul>    <li *ngFor="let item of fruits; let key=index;">          <span *ngIf="key==1" class="red-list">{{item}}</span>        <span *ngIf="key!=1" class="green-list">{{item}}</span>    </li></ul>

4. class --- [ngClass]

app.component.html

<p [ngClass]="{'black': flag, 'red': !flag}" (click)="onChange(flag)">Like</p>

app.component.ts

public flag: boolean = true;

app.component.scss

.black {
  color: black;
}

.red {
  color: red;
}

5. style --- [ngStyle]

app.component.html

<p [ngStyle]="{color: attr}">Red</p>

app.component.ts

public attr: string = "red";