Json Can';t在内部使用*ngIF*ngFor:angular2
我正在使用angular2,我正在绑定来自服务的数据,问题是当我加载数据时,我应该通过id对其进行过滤,这是我应该做的:Json Can';t在内部使用*ngIF*ngFor:angular2,json,typescript,angular,angular2-directives,angular2-services,Json,Typescript,Angular,Angular2 Directives,Angular2 Services,我正在使用angular2,我正在绑定来自服务的数据,问题是当我加载数据时,我应该通过id对其进行过滤,这是我应该做的: <md-radio-button *ngFor="#item of items_list" *ngIf="item.id=1" value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}} </m
<md-radio-button
*ngFor="#item of items_list"
*ngIf="item.id=1"
value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}}
</md-radio-button>
顺便说一下,我只希望接受id=1的数据,但我看到了这个错误:
EXCEPTION: Template parse errors:
Parser Error: Bindings cannot contain assignments at column 14 in [ngIf item.id=1] in RadioFormesType1Component@10:16 ("
<md-radio-button
*ngFor="#item of items_list"
[ERROR ->]*ngIf="item.id=1"
value="{{item.value}}" class="{{item.class}}" checked="{{item.check"): RadioFormesType1Component@10:16
异常:模板分析错误:
分析器错误:绑定不能在中[ngIf item.id=1]的第14列包含赋值RadioFormesType1Component@10:16 ("
]*ngIf=“item.id=1”
value=“{item.value}}”class=“{{item.class}}”checked=“{item.check”):RadioFormesType1Component@10:16
那么,有没有建议同时使用ngif和ngfor?您可以使用以下方法:
*ngIf="item.id===1"
而不是
*ngIf="item.id=1"
您尝试将某些内容分配到id
属性(operator=
),而不是测试其值(operator=
或==
)
此外,不支持同一元素上的ngFor和ngIf。您可以尝试以下操作:
<div *ngFor="#item of items_list">
<md-radio-button
*ngIf="item.id===1"
value="{{item.value}}" class="{{item.class}}"
checked="{{item.checked}}">
{{item.label}}
</md-radio-button>
</div>
{{item.label}
或
{{item.label}
*ngIf
和*ngFor
在同一标记上不受支持。您需要为其中一个标记使用带有显式
标记的长表单
更新
不要使用
而使用
,它允许使用与内联*ngIf
和*ngFor
相同的语法
<ng-container *ngFor="#item of items_list">
<md-radio-button
*ngIf="item.id=1"
value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}}
</md-radio-button>
</ng-container>
{{item.label}
另一个解决方案是创建自定义筛选:
并在组件中这样使用它:
<md-radio-button
*ngFor="#item of items_list | filter:{id: 1}"
value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}}
</md-radio-button>
@Component({
// ...
pipes: [FilterPipe]
})
演示:谢谢,但问题仍然存在异常:TypeError:无法读取[item.id==1]中未定义的属性“id”RadioFormesType1Component@11:16]事实上,您需要创建一个子元素来应用ngIf
。同一元素上的ngFor
和ngIf
都不受支持…
标记不起作用,而我使用了
是的,最好的解决方案是使用,因为更新就像一个charmThanks,效果很好!简单,甚至比答案更简单:filter t在组件中添加数据,然后将其传递到视图中,根本不需要在视图中执行此操作。对于Angular 4,您需要将管道添加到包含要使用管道的组件的模块的声明数组中。
import {Pipe} from 'angular2/core';
@Pipe({name: 'filter'})
export class FilterPipe {
transform(value, filters) {
var filter = function(obj, filters) {
return Object.keys(filters).every(prop => obj[prop] === filters[prop])
}
return value.filter(obj => filter(obj, filters[0]));
}
}
<md-radio-button
*ngFor="#item of items_list | filter:{id: 1}"
value="{{item.value}}" class="{{item.class}}" checked="{{item.checked}}"> {{item.label}}
</md-radio-button>
@Component({
// ...
pipes: [FilterPipe]
})