根据服务响应动态Show/Hide输入框

Dynamically Show/Hide input box based on Service Response

我有一个场景,如果我点击单选按钮,会出现 5 个输入文本框 initially.But 当我点击单选按钮时,将发送服务请求并根据响应,我需要隐藏一些不需要的文本框。

例如:

<input id="1" [(ngModel)]="name"></input>
<input id="2" [(ngModel)]="dob"></input>
<input id="3" [(ngModel)]="city"></input>
<input id="4" [(ngModel)]="state"></input>
<input id="5" [(ngModel)]="country"></input>

服务响应:

{
"id": 1,
"value": "First",
},
{
"id": 2,
"value": "Second",
}

所以现在我需要隐藏除 id = 1 和 2 之外的所有输入元素。

这个方法我试过了,效果不错

<div *ngFor="let res of response">
<input id="1" *ngIf="res.id===1" [(ngModel)]="name"></input>
<input id="2" *ngIf="res.id===2" [(ngModel)]="dob"></input>
<input id="3" *ngIf="res.id===3" [(ngModel)]="city"></input>
<input id="4" *ngIf="res.id===4" [(ngModel)]="state"></input>
<input id="5" *ngIf="res.id===5" [(ngModel)]="country"></input>
</div>

但这种方法似乎并不理想,因为会发生不必要的循环。

有没有更好的方法来满足我的需求?

P.S : id 属性在这里只是一个占位符

直接循环input即可实现。每当 response 变量获得新值时,它会自动更新 dom

<input *ngFor="let res of response" id="{{res.id}}"></input>

好的,因为您已经编辑了代码,现在看来,只有元素迭代不起作用。您当前的方法对此还不错,但我可以建议另一种方法。

<input *ngFor="let res of response" id="{{res.id}}" [(ngModel)]="binding[res.id]"></input>

并且在你的绑定中,你可以有一个类似的数组

let binding = [1:"name",2:"dob",3:"city",4:"state",5:"country"]