gpt4 book ai didi

html - Angular 2 在动态生成的 "list"中向新元素添加高亮显示

转载 作者:行者123 更新时间:2023-11-28 03:44:32 30 4
gpt4 key购买 nike

我有一个连接数组,我使用 angular 2 和 typescript 显示这些连接,如下所示:

 <div class="list-item" *ngFor="let con of connectors; let i = index" id="con{{i}}" (click)="connectorSelected(con,i)">
<label class="list-name">{{con.name || "No Available Name"}}</label>
<label class="list-desc">{{con.description}}</label>
</div>

所以基本上当我选择一个连接时,它会在 typescript 中的 typescript 函数 connectorSelected 中突出显示。

private connectorSelected(con: ConnectorModel, index: number) {
this.removeSelectionOnAllFields();
let selectedElement = document.getElementById("con" + index);
selectedElement.className += " selected"
this.conStatus = SaveStatus.UptoDate;
}

private removeSelectionOnAllFields() {
let allClassesHaveSelected = document.getElementsByClassName("selected");
while (allClassesHaveSelected.length) {
allClassesHaveSelected[0].classList.remove("selected");
}
}

但是,当我创建一个新连接时。我向列表中添加一个新连接并尝试突出显示该新创建的连接,但问题是新创建的连接尚未在 HTML5 网页中呈现。这会导致页面抛出错误,因为我们添加到数组的新连接器尚未在 html 页面中创建。因此还没有元素存在,它只是在执行完整个函数后才在网页中创建元素。

新的连接代码:

 private newConnector(): void {

let newConenctor: ConnectorModel = new ConnectorModel();
this.connectors.push(newConenctor);
let index: number = this.connectors.length - 1;
this.removeSelectionOnAllFields();
let selectedElement = document.getElementById("con" + index);
selectedElement.className += " selected"
}

我想知道我应该如何处理这个问题?

最佳答案

这是因为 Angular 不触发变化检测。

为了解决这个问题,你应该复制你的数组。

this.connectors.push(newConenctor);
this.connectors = this.connectors.slice(0);

否则就像我在评论中所说的那样,我建议您使用指令 [ngClass],它更简单,您不必使用全局文档。

您可以在此处找到文档:https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

关于html - Angular 2 在动态生成的 "list"中向新元素添加高亮显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44056154/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com