angular: 通过两个 ngFors 更新 dom 的指定部分

angular: update specify part of dom by two ngFors

我有一个问题,不知道是否可以在 angular 中执行此操作。

我在HTML中有一个简单的代码:

<div >
    <div *ngFor="let item of apiNames, let i = index" class="rescontainer">
        <div class="resbox headline">
            <strong>Name:</strong> {{item}}
            <span class="extra" (click)="getApiInfo($event, i)">mehr Info</span>
        </div>

        <div id="resMoreBox{{i}}">
            <div *ngFor="let item of apiRes, trackBy: trackByFn" >
                <div class="resbox" *ngIf="item['ADS Container']">
                    <strong>ADS Container:</strong> {{item['ADS Container']}}
                </div>
                ...
            </div>
        </div>
    </div>
</div>

"magic"来自点击事件(click)="getApiInfo($event, i)。这个运行一个http.get。这工作正常,结果是:

[{…}]
0: {PK: 81, IconIndex: "6_1", Name: "VKNE2004", Current Scan: null, PWD Last Set: 4, …}

结果始终是第一个 ngFor 的其中一项的一部分:

ngFor1 = Itemname1
------ngFor2 Apires
ngFor1 = Itemname2
------ngFor2 Apires
ngFor1 = Itemname3
------ngFor2 Apires
....

现在我想更新那里的圆顶,它适合第一个 ngFor 中的项目。

!API RES get Itemname2!
ngFor1 = Itemname1
------ngFor2 Apires
ngFor1 = Itemname2
------ngFor2 Apires --> UPDATE DOM
ngFor1 = Itemname3
------ngFor2 Apires
....

问题是,angular 在第一个 ngFor 的每个 Item 中更新第二个 ngFor 的内容。

是的...这很正常^^

所以问题是,是否可以只更新第一个 ngFor 的特定部分?也许是名字?

我尝试使用 trackBy,但它不起作用。那么请问大家有解决问题的想法吗?

您可以执行以下操作:

更改您的 apiNames 数据结构。例子:

apiNames = ['/api1', '/api2', '/api3'];

const apisData = this.apiNames.map((apiName) => {
  return {
    apiName: apiName,
    data : []
  };
});

现在在您的模板中使用 apisData 并将数据属性绑定到下一个 ngFor

<div *ngFor="let item of apisData , let i = index" class="rescontainer">
    <div class="resbox headline">
        <strong>Name:</strong> {{item.apiName}}
        <span class="extra" (click)="getApiInfo($event, item)">mehr Info</span>
    </div>

    <div id="resMoreBox{{i}}">
        <div *ngFor="let apiData of item.data, trackBy: trackByFn" >
            <div class="resbox" *ngIf="apiData['ADS Container']">
                <strong>ADS Container:</strong> {{apiData['ADS Container']}}
            </div>
            ...
        </div>
    </div>
</div>

然后更改 getApiInfo 实现以管理 item.data :)

getApiInfo($event, item) {
  this.httpClient.get(item.apiName + '/blablabla').subcribe( (result) => {
    item.data = result;
  });
}