Search code examples
angularjscontainersngfor

Angular Use Function in Container Context


I want to set up a checkbox structure and I want to handle it dynamically. I have an object response returned from my service. However, when I use this function in context, I get a string return and I cannot use ngFor.

form.demo.component.ts

   getElementChoicesByNKey(nkey:string):choiceModel[]{
     var element = this.findInComponentsByNKey(nkey);
     var res = element.Choices;
     return res;
   }

this function gives the correct return.

form.demo.component.html

...
                        <ng-container *ngIf="item.Type == 'Choice'">
                          <ng-container *ngTemplateOutlet="choiceTheme; context:{ Id: item.Id, Label: item.Label, Choices: getElementChoicesByNKey(item.Id) }"></ng-container> 
                        </ng-container>
...
                <ng-template #choiceTheme let-Id="Id" let-Label="Label" let-Choices="Choices">
                  <nz-form-item>                      
                    <nz-form-label nzFor="Id">{{Label}}</nz-form-label>
                    <nz-form-control [formControlName]="Id" nzErrorTip="{{ 'form.requiredText' | translate }}"> 
                      <p>{{Choices.length}}</p>
                      <div *ngFor="let item of Choices">
                        <p>test</p>
                      </div>                               
                    </nz-form-control>
                  </nz-form-item>            
                </ng-template>
...

here Choices appears as string and won't let me use ngFor. I am getting an error as below.

Cannot find a differ supporting object '[ { label: 'Apple', value: 'Apple', checked: true }, { label: 'Pear', value: 'Pear', checked: false }, { label: 'Orange', value: 'Orange', checked: false } ]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

What is the point I missed? Thank you for your help.


Solution

  • Use *ngFor="let item of getChoices(Choices)" in template and in component.ts

    getChoices(choiceStr) {
        return JSON.parse(choiceStr);
    }
    

    Since you are getting Choices as a string, parse the string to an array inorder for ngFor to work