Eli*_*off 7 typescript ngfor angular
我试图使用*ngFor但迭代迭代对象的属性in.当我尝试这样做
@Controller({
selector: 'sample-controller',
template: `
<ul>
<li *ngFor="let i in obj">
<b>{{i}}</b>: {{obj[i]}}
</li>
</ul>`
})
class SampleController {
obj = {a: 1, b: 2}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:
无法绑定到'ngForIn',因为它不是'li'的已知属性.
我已经包含FormsModule并BrowserModule在imports一节@NgModule此组件.
是否有可能使用ngForIn上li,如果没有有一个惯用的方法吗?
正如评论中提到的AJT_82,您可以为此目的创建特殊指令.它将基于NgForOf<T>指令:
interface NgForInChanges extends SimpleChanges {
ngForIn?: SimpleChange;
ngForOf?: SimpleChange;
}
@Directive({
selector: '[ngFor][ngForIn]'
})
export class NgForIn<T> extends NgForOf<T> implements OnChanges {
@Input() ngForIn: any;
ngOnChanges(changes: NgForInChanges): void {
if (changes.ngForIn) {
this.ngForOf = Object.keys(this.ngForIn) as Array<any>;
const change = changes.ngForIn;
const currentValue = Object.keys(change.currentValue);
const previousValue = change.previousValue ?
Object.keys(change.previousValue) : undefined;
changes.ngForOf = new SimpleChange(previousValue, currentValue, change.firstChange);
super.ngOnChanges(changes);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2483 次 |
| 最近记录: |