ngForIn可用于角4吗?

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'的已知属性.

我已经包含FormsModuleBrowserModuleimports一节@NgModule此组件.

是否有可能使用ngForInli,如果没有有一个惯用的方法吗?

yur*_*zui 7

正如评论中提到的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)

Plunker示例