使用 *ngIf 指令有条件地更改输出

17 Mar 2025 | 阅读 2 分钟

示例

component.ts 文件

component.html 文件

输出

输出将如下所示。

Use of *ngIf directive to change the output conditionally

当我们更改输入值并单击“添加服务器”按钮时,您将看到以下结果

Use of *ngIf directive to change the output conditionally

您可以在上面的示例中看到,通过使用 *ngIf 指令,我们可以更改条件以相应地显示输出。

您可以在添加服务器之前和之后检查输出的源代码。您将清楚地看到差异。

添加服务器之前

Use of *ngIf directive to change the output conditionally

添加服务器之后

Use of *ngIf directive to change the output conditionally

因此,您可以看到结构指令如何更改 DOM。

*ngIf 指令与 Else 条件

您还可以将 Else 条件与 *ngIf 指令一起使用。如果 *ngIf 不为真,它用于显示输出。让我们对 component.html 文件进行一些更改。

component.html 文件

输出

Use of *ngIf directive to change the output conditionally

单击“添加服务器”按钮后

Use of *ngIf directive to change the output conditionally

您还可以使用求反 (!) 符号来检查它的相反情况。