1

如何根据 dom 元素的 id 或不涉及事件的其他内容访问 dom 元素后面的对象?

例如我有:

arr1 = [{a:1, b:2}, {a:5, b:10}, {a:20, b:50}];

<li *ngFor="let obj of arr1; let indexObj=index" id="{{indexObj}}">
    {{obj.a}}
</li>

document.getElementById("1");

但我希望能够访问与 li DOM 元素关联的属性 a 和 b

编辑:问题不够清楚,所以我会尝试扩展。你通常会做什么

<li *ngFor="let obj of arr1; let indexObj=index" id="{{indexObj}}" (click)="somefunc(obj)">
        {{obj.a}}
 </li>

然后我可以在我的函数中访问 obj

somefunc(obj) {
    console.log(obj.a);
}

somefunc我想在没有点击事件或任何其他事件的情况下实现我正在做的事情。因此,例如,我可以通过document.getElementById("1");或通过访问 DOM 元素 li,this.eleRef.nativeElement.querySelector('#1')但我想访问与 DOM 元素关联的 obj,所以我希望能够做这样的事情。

somefunc2() {
    let el = document.getElementById("1");
    console.log(obj.a associated with el);
}
4

4 回答 4

1

如果您知道 id,则find在数据源中使用该数组。

   const trgItem = arr1.find(item => return item.a === 1);

您还应该以这种方式更改 html 以正确设置 id:

<ul>
    <li *ngFor="let obj of arr1; let indexObj=index" id="{{indexObj}}">
        {{obj.a}}
    </li>
<ul>

如果您知道索引,请使用indexOf(0)数组的功能。

如果你想在某事发生时得到它,那么你只能通过一个事件来做到这一点。

于 2019-12-05T10:45:21.520 回答
1

它不起作用,因为您没有插入 id ...

你的 html 应该是:

<li *ngFor="let obj of arr1; index as indexObj" id="{{indexObj}}">
  {{obj.a}} //also you had a typo here (ibj instead of obj)
</li>

编辑更新的问题:

由于您知道 id,要检索数组中的项目,您可以这样做:

const arr1 = [{a:1, b:2}, {a:5, b:10}, {a:20, b:50}];


const id = 1;
const item = arr1[id];
console.log(item, item.a, item.b);

于 2019-12-05T10:52:45.740 回答
0

我创建了stackblitz工作示例供您使用,像这样修改您的组件代码-

 arr1 = [{ a: 1, b: 2 }, { a: 5, b: 10 }, { a: 20, b: 50 }];

  ngAfterViewInit() {
    const val = Number(document.getElementById('1').innerHTML);
    console.log(this.arr1.find(ele => ele.a === val)); // you'll get the object here.
  }
于 2019-12-05T11:47:52.780 回答
0

@ViewChild您可以通过使用and来获取元素的对象或获取所有子对象@ViewChildren

@ViewChildren:

@Component({
  selector: 'my-app',
  template: `
    <alert></alert>
    <alert type="danger"></alert>
    <alert type="info"></alert>
  `,
})
export class App {
  @ViewChildren(AlertComponent) alerts: QueryList<AlertComponent>

  ngAfterViewInit() {
    // Here you get all instances of the alert component
    this.alerts.forEach(alertInstance => console.log(alertInstance));
  }
}

有关这方面的更多信息:https ://angular.io/api/core/ViewChildren

于 2019-12-05T12:03:44.783 回答