Can ngForIn be used in angular 4?

雨燕双飞 提交于 2019-12-07 00:30:34

问题


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

I get the error message:

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

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

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


回答1:


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




回答2:


The easiest approach would be to turn your object into an array using Object.values() and Object.keys(). Check out this plunker for an example.

If you want access to the keys as well as the value you can include an index in your *ngFor.

Template:

<ul>
  <li *ngFor="let item of array; let index = index;">
    <b>{{keys[index]}}</b> value: {{item}}, index: {{index}}
  </li>
</ul>

Component TypeScript:

export class App {
  obj = {a: 1, b: 2}
  array = [];
  keys = [];
  constructor() {
  }

  ngOnInit() {
  this.array = Object.values(this.obj);
  this.keys = Object.keys(this.obj);
  }
}



回答3:


Object.keys and Object.values can be assigned to public properties on the component and then they are available as functions in a template. eg

//somewhere in the component
public objectKeys = Object.keys;
public objectValues = Object.values;

//somewhere in template
...*ngFor="let key of objectKeys(someObject)"...


来源:https://stackoverflow.com/questions/45151334/can-ngforin-be-used-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!