由于某些原因,ngIf
似乎不起作用。
如果我添加*ngIf="main.visible"
,代码就会失败,如果我删除它,代码就会正常工作。
任何想法
下面是我的例子:http://codepen.io/patrioticcow/pen/YqxVNq?editors=1010
UPDATE:我接受ngIf
未在代码中的那个位置解析的答案。如果你读到这篇文章,并且你认为这是一个错误(可能会得到解决),请在评论或其他地方指出。感谢
// add component
(function(app) {
app.AppComponent = ng.core
.Component({
selector: 'my-app',
template: `<div *ngFor="#main of content; #i=index" *ngIf="main.visible">{{main.title}} - {{main.visible}} </div>`
})
.Class({
constructor: function() {
this.content = [{
title: 'test a',
visible: true
}, {
title: 'test b',
visible: true
}, {
title: 'test c',
visible: true
}, {
title: 'test d',
visible: false
}, ];
}
});
})(window.app || (window.app = {}));
// bootstrap app
(function(app) {
document.addEventListener('DOMContentLoaded', function() {
ng.platform.browser.bootstrap(app.AppComponent);
});
})(window.app || (window.app = {}));
html {
background: linear-gradient(#0143A3, #0273D4);
height: 100%;
}
body {
text-align: center;
color: #fff;
padding-top: 180px;
}
<script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/Rx.umd.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/angular2-all.umd.dev.js"></script>
<my-app>
</my-app>
我认为局部变量main在这一点上没有被解析。创建一个额外的div,并在*ngFor 中使用*ngIf
更新至angular2 beta 8及以上版本
现在,从angular2β8开始,我们可以在同一组件上使用*ngIf and
*ngFor,请参见此处或者,我们可以使用-
ng对于使用模板:-
<template ngFor #abc [ngForOf]="someArray">
code here....
</template>
ng如果使用模板:-
<template [ngIf]="show">
code here....
</template>
*ngFor
和*ngIf
<div *ngFor="let main of content; let i=index" *ngIf="main.visible">
{{main.title}} - {{main.visible}}
</div>
相反,完整的语法需要至少用于两者中的一个,如
<template ngFor let-main [ngForOf]="content" let-i="index">
<div *ngIf="main.visible">
{{main.title}} - {{main.visible}}
</div>
</template>
或
<template [ngIf]="condition">
<div *ngFor="let main of content; #i=index">
{{main.title}} - {{main.visible}}
</div>
</template>
这取决于所需的行为
另请参见CodePen示例