假设我有
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>
但是有没有办法引入模板变量来简洁地做到这一点?
如果您不喜欢 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);