如何为 Angular 表达式使用别名?

Har*_*Das 3 angular

我正在使用 Angular 7

我有以下模板

<div>
{{myService.userInfo.firstName}} {{myService.userInfo.lastName}}
</div>
Run Code Online (Sandbox Code Playgroud)

我想通过替换user而不是使其简短myService.userInfo

<div>
{{user.firstName}} {{user.lastName}}
</div>
Run Code Online (Sandbox Code Playgroud)

我怎样才能像 AngularJS 中的 ng-init 一样做到这一点。

Sad*_*jee 10

是的,您可以借助 或 来完成此NgIf操作NgForOf

解决方案:

所以,就你的情况而言,它将是:

<div *ngIf="myService.userInfo as user">
  {{user.firstName}} {{user.lastName}}
</div>
Run Code Online (Sandbox Code Playgroud)

供参考的角度文档:
https://angular.io/api/common/NgIf#storing-conditional-result-in-a-variable https://angular.io/api/common/NgForOf#local-variables

  • 删除第一个片段。第二个片段可能有效。但如果有一个直接的解决方案就太好了。这是一种解决问题的 hack。 (2认同)

Kis*_*mar 6

创建一个将返回 userinfo 对象的 getter 属性

 get user(){
      return this.myService.userInfo;
 }
Run Code Online (Sandbox Code Playgroud)

并使用像

<div>
   {{user.firstName}} {{user.lastName}}
</div>
Run Code Online (Sandbox Code Playgroud)