Home > Enterprise >  Iterate over properties and assign values in angular
Iterate over properties and assign values in angular

Time:05-12

I have a component with properties. I want to assign new values to those properties when the input changes. Because I have many properties (they are used as text in an svg template) i want to iterate over them and assign new values to them. I tried the following but without success and I can't figure out any working way.

export class MyComponent implements OnInit {

@Input() aMapWithNewNumbers: Map<string,number>;

PropertieA = 1;
PropertieB = 2;
...
PropertieZ = 3;

ngOnChanges(changes: SimpleChanges): void {
  if(changes.aMapWithNewNumbers.currentValue){
    const list = Object.key(this);
    list.forEach((elem) => {
      if(this.aMapWithNewNumbers.get(elem) != undefined){
        const num = this.aMapWithNewNumbers.get(elem);
        elem = num; //<= this doesn't work since elem is of type string
      }
    });
  }
}
...

Any help appreciated!

CodePudding user response:

Iterating over the keys of a component object is not a common pattern, and usually another data structure can be used instead. In this case, I think you could just use the existing map Input in your html by binding to the it directly: [myProp]="aMapWithNewNumbers?.get('myPropertyName')".

CodePudding user response:

You could try something like:

var myProperties = {
    property1: true,
    property2: 25,
    property3: 'PropertyValue',
  };

for (const property in myProperties) {
    if (property === 'property1')
    {
        myProperties[property] = false;
    }
}

for (const property in myProperties) {
    
    console.log(property);
    console.log(myProperties[property]);
}
  • Related