我已经获得了公共值cursorUrl和检查URL是否存在的方法,如果它存在,它分配了urlCursor='pointer'如果它不存在,它分配了urlCursor='text'
这个方法似乎工作得很好,但是它将每个项都分配给urlCursor='pointer',即使控制台日志打印出它应该是

pointer
text
text
text

这是我的方法:
ngOnChanges(changes: any) {
    let index = 0;
    this.urlCursor =
        this.checkUrl(changes.items.currentValue[0].redirectionViewUrl);
    index++;
    console.log(this.urlCursor);
}

这是HTML:
<div class="items" #item(window:resize)="itemResizeHandler();" >
    <app-item
        *ngFor="let item of items"
        class="item-element"
        [ngStyle]="{'cursor': urlCursor}"
        [dataMode]="item.dataMode"
        [redirectionViewUrl]="item.redirectionViewUrl"
    ></app-item>
</div>

有人知道为什么它不能正确绑定吗?

最佳答案

绑定工作正常。您的urlCursor不是一个变量数组,而是一个单独的变量,因此最后分配给它的任何内容都将用于所有值。尝试修改ts文件中的代码,如下所示:

public urlCursor: string[] = []
...
ngOnChanges(changes: any) {
    ...
    this.urlCursor = [];
    this.urlCursor.push(
      this.checkUrl(changes.items.currentValue[0].redirectionViewUrl)
    );
    ...
}

就像是:
<app-item
  *ngFor="let item of items; let ind=index"
   class="item-element"
   [ngStyle]="{'cursor': urlCursor[ind]}"
   [dataMode]="item.dataMode"
   [redirectionViewUrl]="item.redirectionViewUrl"
></app-item>

关于angular - ngOnChanges Angular 2没有分配不同的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52430580/

10-12 07:32
查看更多