Search code examples
angulartypescriptngoninit

this.results.rulesFired not getting defined


I have the following table rows

<tr *ngFor="let firedRule of splitRules(results.rulesFired); let rowNumber = index"
            [class.added]="isAdd(firedRule)"
            [class.removed]="isRemove(firedRule)"
            [class.modified]="isModify(firedRule)">

Here is the splitRules function, which basically takes in a list of rules and break down each rule into new properties:

splitRules(firedRules: FiredRule[]) {
const regExRowNumber = /row\s*([0-9]+)/;
let rowMatch = [];
firedRules.forEach(rule => {
  let name = '';
  name = rule.ruleName.toLowerCase();
  rowMatch = regExRowNumber.exec(name);
  const rowNumber = rowMatch[1];
  const ruleName = name.substr(rowMatch[0].length).split('-')[0];
  const conditionsMatched = name.substr(rowMatch[0].length).split('-')[1];
  rule.groupName = ruleName.trim().replace('!', ': ').split(':')[0];
  rule.definitionName = ruleName.trim().replace('!', ': ').split(':')[1];
  rule.rowNumber = rowNumber;
  rule.conditionsMatched = conditionsMatched.trim();
  rowMatch = [];
});
return firedRules;

}

It's not a good practice to call the splitRules method inside the html, so I tried to call it on ngOnInit like this:

@Input() results: RulesEngineResponse;
ngOnInit(): void {
   this.results.rulesFired = this.splitRules(this.results.rulesFired);
}

And remove the call from html, however, I got ERROR TypeError: Cannot read property 'rulesFired' of null, is there anyway to fix this?

I would appreciate any help.


Solution

  • It may be because you are passing Input() results value as null from its parent component. Make sure you pass the Input() results value to that component. If there is a scenario that you will pass that Input() results value later, then make a null check before you call this.results.