我在Angular的模板/组件设计中遇到了一些问题。 让我们看看这个简单的样本。
import {Component} from "@angular/core";
@Component({
selector: "test",
template: `
<ul *ngFor="let l of lst">
<li *ngIf="l > 3">{{ l }}</li>
</ul>
The count is ...
`
})
export class TestComponent
{
lst : Array <number> = [1, 3, 5, 9];
}
我的模板中有逻辑(全部显示&gt; 2)。
现在最后我想知道屏幕上有多少项目。
我不喜欢在类和模板中共享逻辑。
处理它的一种方法是将逻辑放在类中的数据旁边(并且仅在那里)并使用已经过滤的数据 INSTEAD对所有数据进行操作并在模板中具有逻辑 然后在课堂上很容易计算出来。
还有另一种方法 - 让我们说操纵模板中的反变量来影响类吗? 我在调用{{}}中的函数时尝试了它,但这种方法无法正常工作。
答案 0 :(得分:1)
你说你应该在班上实现你的业务逻辑。这是最好的地方,将您的业务逻辑保持在一个地方,提供最佳的关注点分离。试图做出你建议的替代方案毫无意义。这意味着跳过篮球并使不必要的事情复杂化。在课堂上完成工作总能为您提供更多控制,灵活性和可扩展性。最好养成这种习惯。
答案 1 :(得分:1)
为您的逻辑创建单独的列表,该列表是您lst
的子集。
然后,您可以在组件类中使用逻辑,并在模板中显示。
import {Component} from "@angular/core";
@Component({
selector: "test",
template: `
<ul *ngFor="let l of otherList">
<li>{{ l }}</li>
</ul>
The count is {{otherList.length}}
`
})
export class TestComponent
{
lst : Array <number> = [1, 3, 5, 9];
otherList:Array<number> = [];
constructor(){
this.doLogic();
}
doLogic(){
lst.forEach(item=>{
if(item>3){
otherList.push(item);
}
});
}
}