Angular 17 中的声明式控制流 |如何在 Angular 17 中实现 @If @else @switch

问题描述 投票:0回答:1

为了让前端更加美观且易于理解,我实现了声明式的控制流语法。

@如果(显示){

我是可见的。

} @别的 {

我隐藏了。

}

要在项目中实现声明式控制流,请使用以下解决方案

for循环

@Component({
  selector: 'app-stackoverflow',
  templateUrl: './app.stackoverflow.html',
  styleUrls: ['./app.stackoverflow.scss']
})
export class AppStackoverflow {
  skills = ['Java', 'JS', 'TS', 'Node'];
}
<ul>
  @for (item of skills; track item; let i = $index, f = $first; let l = $last, ev = $even, o = $odd; let co = $count) {
    <li>{{item}}
      <ul>
        <li>Index - {{i}}</li>
        <li>Is First - {{f}}</li>
        <li>Is Last - {{l}}</li>
        <li>Is even - {{ev}}</li>
        <li>Is odd - {{o}}</li>
        <li>Count - {{co}}</li>
      </ul>
    </li>
  } @empty {
    <li>No item</li>
  }
</ul>

@如果

@if (user.isHuman) {
  <human-profile [data]="user" />
} @else if (user.isRobot) {
  <!-- robot users are rare, so load their profiles lazily -->
  @defer {
    <robot-profile [data]="user" />
  }
} @else {
  <p>The profile is unknown!
}

@开关

@switch (caseNo) {
  @case (1) {
    <span>Rendering case 1</span>
  }
  @case (2) {
    <span>Rendering case 2</span>
  }
  @case (3) {
    <span>Rendering case 3</span>
  }
  @default {
    <span>Rendering default</span>
  }
}
angular angular-directive angular17
1个回答
0
投票

在 Angular 中启用新的控制流需要做什么

angular.json

{
  "angularCompilerOptions": {
    ....
    "_enabledBlockTypes": [
      "if", "switch", "for"
    ]
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.