ngForIn可以在角度4中使用吗? [英] Can ngForIn be used in angular 4?

查看:176
本文介绍了ngForIn可以在角度4中使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用*ngFor但使用in遍历对象的属性.当我尝试这样做

I am trying to iterate over the properties of an object using *ngFor but using in. When I try to do this

@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}
}

我收到错误消息:

由于它不是'li'的已知属性,因此无法绑定到'ngForIn'.

Can't bind to 'ngForIn' since it isn't a known property of 'li'.

我已经在@NgModuleimports部分中包含了FormsModuleBrowserModule.

I have included FormsModule and BrowserModule in the imports section of the @NgModule for this component.

是否可以在li上使用ngForIn,如果没有,这是惯用的选择吗?

Is it possible to use ngForIn on li and if not is there an idiomatic alternative?

推荐答案

正如注释中提到的AJT_82一样,您可以为此目的创建特殊指令.它将基于NgForOf<T>指令:

As AJT_82 mentioned in comment you can create special directive for such purposes. It will be based on NgForOf<T> directive:

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);
    }
  }
}

柱塞示例

Plunker Example

这篇关于ngForIn可以在角度4中使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆