Is it possible to use ngForIn in angular 4?

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

@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 an error message:

You cannot bind to 'ngForIn', since this is not a known property of 'li'.

I turned on FormsModuleand BrowserModulein the section imports @NgModulefor this component.

Is it possible to use ngForInon li, and if not, is there an idiomatic alternative?

+6
source share
4 answers

As mentioned in AJT_82 comment, you can create a special directive for such purposes. It will be based on the directive 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);
    }
  }
}

Plunger example

+6

- Object.values() Object.keys(). .

, , *ngFor.

:

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

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

, , , 7.

[ts] The property 'ngOnChanges' does not exist in the type 'NgForOf'. [2339]

Does anyone have a solution or workaround for this?

0
source

Object.keysand Object.valuesyou can assign it to the public properties of the component, and then they will be available as functions in the template. eg

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

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

Source: https://habr.com/ru/post/1681636/


All Articles