如何在模板表达式中使用信号?

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

假设我有

interface Point {
  x:number;
  y:number;
}

@Component(...)
class PointComponent {
  point = signal<Point>({x:0, y:0});
}

现在我可以在模板中做到这一点

@if(point(); as point) {
  <pre> x: {{point.x}}, y: {{point.y}} </pre>
}

但是我使用@if作为辅助控制流块,因为我无法以其他方式引入模板变量。

我当然能做到

<pre> x: {{point().x}}, y: {{point().y}} </pre>

但是有没有办法引入模板变量来简洁地做到这一点?

angular signals
1个回答
0
投票

如果您不喜欢 if 语法,您可以使用计算来执行此操作,但

@if
似乎是最少的代码选项

import { Component, signal, computed } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
interface Point {
  x:number;
  y:number;
}

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    @if(point(); as point) {
      <pre> x: {{point.x}}, y: {{point.y}} </pre>
    }
    <pre> x: {{x()}}, y: {{y()}} </pre>
  `,
})
export class App {
  point = signal<Point>({x:0, y:0});
  name = 'Angular';
  x = computed(() => this.point().x);
  y = computed(() => this.point().y);
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.