我如何让 ng-if 重申数组?
How do i get ng-if to reiterate the array?
我有一个带有 *ng-for
的元素。它完美地呈现数据(一组对象)。如果我添加一个元素,那么我会在我的视图中看到新数据。
<div *ng-for="#item of items" [attr.bob]="item.bob" />
如果我修改了项目列表中的项目,我需要它反映在我的视图中,但事实并非如此。我怎样才能做到这一点?我可以触发整个数组的完整渲染 - 我可以通过 adding/removing 元素 - 但这里的最佳实践是什么?也许有一种方法可以 'dirty' #item ?
编辑:我将我的代码改回我无法开始工作的原始版本,因为我刚刚发布的版本确实有效,使这个问题无效。 我仍然很好奇您是否可以手动强制重新迭代 不过我还是把这个问题留了下来。如果您在这里寻找解决方案,我所做的是直接依赖于 属性(索引)而不是嵌套在数组中的对象中。
你不能在某处设置 [attr.something] 的值然后强制刷新吗?
实际上不需要重新迭代。属性绑定到数组的元素,并且会分别改变。数组的变化也会自动显示。
function RandomColorHex(){
return '#'+Math.floor(Math.random()*16777215).toString(16);
}
@Component({
selector: 'app'
})
@View({
template: `
<button (click)="push()">add item</button>
<p *ng-for="#item of items" [style.color]="item.color">{{ item.title }}</p>
`,
directives: [NgFor]
})
class AppComponent{
constructor(){
this.items = [
{title:"foo", color:"red"},
{title:"bar", color:"green"},
{title:"baz", color:"blue"}
];
setInterval(() => {
let randomElement = this.items[Math.floor(Math.random()*this.items.length)];
randomElement.color = RandomColorHex();
}, 500);
}
push(){
this.items.push({title:"i'm new here", color:"black"});
}
}
我有一个带有 *ng-for
的元素。它完美地呈现数据(一组对象)。如果我添加一个元素,那么我会在我的视图中看到新数据。
<div *ng-for="#item of items" [attr.bob]="item.bob" />
如果我修改了项目列表中的项目,我需要它反映在我的视图中,但事实并非如此。我怎样才能做到这一点?我可以触发整个数组的完整渲染 - 我可以通过 adding/removing 元素 - 但这里的最佳实践是什么?也许有一种方法可以 'dirty' #item ?
编辑:我将我的代码改回我无法开始工作的原始版本,因为我刚刚发布的版本确实有效,使这个问题无效。 我仍然很好奇您是否可以手动强制重新迭代 不过我还是把这个问题留了下来。如果您在这里寻找解决方案,我所做的是直接依赖于 属性(索引)而不是嵌套在数组中的对象中。
你不能在某处设置 [attr.something] 的值然后强制刷新吗?
实际上不需要重新迭代。属性绑定到数组的元素,并且会分别改变。数组的变化也会自动显示。
function RandomColorHex(){
return '#'+Math.floor(Math.random()*16777215).toString(16);
}
@Component({
selector: 'app'
})
@View({
template: `
<button (click)="push()">add item</button>
<p *ng-for="#item of items" [style.color]="item.color">{{ item.title }}</p>
`,
directives: [NgFor]
})
class AppComponent{
constructor(){
this.items = [
{title:"foo", color:"red"},
{title:"bar", color:"green"},
{title:"baz", color:"blue"}
];
setInterval(() => {
let randomElement = this.items[Math.floor(Math.random()*this.items.length)];
randomElement.color = RandomColorHex();
}, 500);
}
push(){
this.items.push({title:"i'm new here", color:"black"});
}
}