Angular 在容器上下文中使用函数
Angular Use Function in Container Context
我想设置一个复选框结构并且我想动态地处理它。我有一个来自我的服务的对象响应 return。但是,当我在上下文中使用此函数时,我得到一个字符串 return 并且我无法使用 ngFor.
form.demo.component.ts
getElementChoicesByNKey(nkey:string):choiceModel[]{
var element = this.findInComponentsByNKey(nkey);
var res = element.Choices;
return res;
}
此函数给出正确的 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>
...
此处 Choices 显示为字符串,不允许我使用 ngFor。我收到如下错误。
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.
我错过了什么?感谢您的帮助。
使用
*ngFor="let item of getChoices(Choices)"
在模板中
在 component.ts
getChoices(choiceStr) {
return JSON.parse(choiceStr);
}
由于您将 Choices
作为字符串获取,因此将字符串解析为数组以便 ngFor
正常工作
我想设置一个复选框结构并且我想动态地处理它。我有一个来自我的服务的对象响应 return。但是,当我在上下文中使用此函数时,我得到一个字符串 return 并且我无法使用 ngFor.
form.demo.component.ts
getElementChoicesByNKey(nkey:string):choiceModel[]{
var element = this.findInComponentsByNKey(nkey);
var res = element.Choices;
return res;
}
此函数给出正确的 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>
...
此处 Choices 显示为字符串,不允许我使用 ngFor。我收到如下错误。
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.
我错过了什么?感谢您的帮助。
使用
*ngFor="let item of getChoices(Choices)"
在模板中
在 component.ts
getChoices(choiceStr) {
return JSON.parse(choiceStr);
}
由于您将 Choices
作为字符串获取,因此将字符串解析为数组以便 ngFor
正常工作