在 Angular 上使用 ngIf Else
 
當我們作為開發人員構建 Web 應用程式時,我們需要設定 Web 應用程式以動態調整頁面; *ngIf 語句變得很方便。 *ngIf 用於操作呈現在頁面上的 HTTP 元素。
它在我們告訴網路應用程式在一些引數到位後執行某個功能的條件下工作。而當這些引數沒有到位時,它應該執行另一種代替。
我們將只使用*ngIf 來執行一些功能。然後我們將把 *ngIf 與 else 語句結合起來,看看有什麼可能。最後,我們將使用 *ngIf else then 組合來操作 HTTP 元素。
在 Angular 中使用*ngIf 作為一個獨立的函式
所以在這裡,我們將使用*ngIf 語句以及 true 或 false 條件。
我們將在 app.component.html 中完成所有工作。
<h1>*ngIf in Angular</h1>
<h2 *ngIf="true">
  Hi, Youtube
</h2>
當*ngIf 條件設定為真時,網頁顯示 Hi, Youtube。一旦更改為 false,Hi, Youtube 將從網頁中消失。
我們也可以像這樣通過 app.component.ts 傳遞函式:
import { Component } from "@angular/core";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "CodeSandbox";
  displayMe=true;
}
然後我們將*ngIf 值更改為 displayMe,如下所示:
<h1>*ngIf in ANgular</h1>
<h2 *ngIf="displayMe">
  Hi, Youtube
</h2>
就像第一個示例一樣,基本規則的工作方式相同。
將 *ngIf 與 else 一起使用
當 *ngIf 條件與 else 語句結合使用時,它可以幫助我們決定在任何時間點我們希望在網頁上顯示什麼內容。
這種方法要求我們在 ng-template 標籤內巢狀我們想要出現在 Hi, Youtube 中的另一個語句。
app.component.html 將如下所示:
<h1>*ngIf in ANgular</h1>
<h2 *ngIf="displayMe else elseBlock">
  Hi, Youtube
</h2>
<ng-template #elseBlock>
<h2>
    Hi, Twitter
    </h2>
</ng-template>
你會注意到我們在*ngIf 條件旁邊使用了 else 語句,這使我們能夠更好地控制網頁的內容。
所以在 app.component.ts 中,當 displayMe 為真值時,Hi, Youtube 將顯示。如果它是假的,嗨,Twitter 將顯示。
在 Angular 中使用 *ngIf 與 else 和 then 語句
在前面的示例中,我們被介紹了 ng-template,它與 else 語句一起使用。當與 *ngIf 和 else 一起使用時,then 語句允許在 ng-template 中操作內容。
對於想要保持結構化且排列良好的程式碼檔案的編碼人員來說,這是一個受歡迎的解決方案。
我們的 app.component.html 將被配置為:
<h1>*ngIf in ANgular</h1>
<h2 *ngIf="displayMe; then ifBlock else elseBlock">
  Hi, Youtube
</h2>
<ng-template #ifBlock>
<h2>
    Hi, Google
    </h2>
</ng-template>
<ng-template #elseBlock>
<h2>
    Hi, Twitter
    </h2>
</ng-template>
所以在 app.component.ts 中,當 displayMe 為真值時,會顯示 Hi, Google,當它是假值時,會顯示 Hi, Twitter。
Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.
LinkedIn