Angular 中的 if...else 語句
我們將介紹如何在 Angular 應用程式中使用 if 語句並討論示例。
在 Angular 中使用 if 語句
在程式設計中,if 語句是邏輯塊。這些條件語句告訴計算機在特定條件為真或假時要做什麼。
在 Web 應用程式的現代時代,if 語句使程式設計師的生活更容易理解何時根據條件執行特定程式碼塊。
我們可以通過不同的方式使用 *ng-if 或我們將在示例中討論的其他簡單方法在 Angular 中使用 if 語句。
讓我們使用以下命令建立一個新應用程式:
# angular
ng new my-app
在 Angular 中建立我們的新應用程式後,我們將使用此命令轉到我們的應用程式目錄。
# angular
cd my-app
現在,讓我們執行我們的應用程式來檢查所有依賴項是否安裝正確。
# angular
ng serve --open
然後,在 app.component.ts 中,我們將變數 statement 設定為 false。我們將使用這個變數來執行我們的程式碼。
# angular
statement = false;
現在,在 app.component.html 中,我們將使用變數 statement 建立一個模板,如果我們將變數設定為 true,它將顯示宣告為真的內容。
如果我們將變數設定為 false,它將顯示語句為 false。
# angular
<hello name="{{ name }}"></hello>
<h2>{{ statement ? 'This statement is True' : 'This statement is false' }}</h2>
讓我們測試我們的應用程式,看看它在更改值 statement 時是否有效。
輸出:

更改語句的值,將其設定為 true,然後檢查它是如何工作的。
輸出:

因此,如你所見,當我們更改 statement 變數的值時,程式碼會執行並使用簡單的語句方法顯示我們想要檢視的值。
讓我們想象一個我們想要在執行 if-else 語句的 div 中顯示的塊。我們可以使用 *ng-if 語句並將 ids 設定為我們想要在條件正確或錯誤時顯示的塊。
我們將設定一個新變數 element 為 1。app.component.ts 中的程式碼如下所示。
# angular
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
statement = true;
element = 1;
}
在 app.component.html 中建立一個模板。我們將有一個帶有*ng-if 語句的 div,它將顯示一個塊 trueBlock,如果 element 的值不是 1,那麼它將顯示 id 為 falseBlock 的塊。
<div *ngIf="element == 1; then trueBlock; else falseBlock"></div>
<ng-template #trueBlock><button>Login</button></ng-template>
<ng-template #falseBlock><button>Logout</button></ng-template>
讓我們看看它是如何工作的。
輸出:

嘗試更改 element 的值並檢查它是如何工作的。
# angular
element = 2;
輸出:

正如你在上面的示例中所看到的,我們可以使用*ng-if 語句並呼叫塊的 id 輕鬆顯示程式碼塊。
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn