Angular 4 |如何访问span元素并为其分配编号?

时间:2017-12-11 01:43:44

标签: angular

如何访问span元素并为其指定编号?

<div class="container">
   <span>one</span>
   <span>two</span>
   <span>tree</span>
   <span>four</span>
   <span>five</span>
</div>

然后结果应该是这样的

one | 1
two | 2
three| 3
four | 4
five | 5

我发现了一些@ViewChildren和本地引用,但是当我访问span元素时,我只得到它的长度。如何访问范围并为其分配编号?

1 个答案:

答案 0 :(得分:4)

不确定您要实现的目标,但您可以这样做,例如这样:

模板:

<div #container class="container">
   <span>one</span>
   <span>two</span>
   <span>tree</span>
   <span>four</span>
   <span>five</span>
</div>

组件:

@Component({/*...*/})
export class SomeComponent implements AfterViewInit {
  @ViewChild('container') public container: ElementRef;

  public ngAfterViewInit() {
    // container will be undefined before this hook
    let spans = this.container.nativeElement.children;
    for (let i in spans) {
      spans[i].innerText += i + 1;
    }
  }
}

但是我认为你可以使用标准的Angular迭代器:

interface Item {
  text: string;
  maybeMoreProperties?: number;
}

@Component({
  template: `<div class="container">
<span *ngFor="let item of items, let i = index">{{item.text}} {{i + 1}}</span>
</div>`
})
export class SomeComponent implements OnInit {
  public items: Array<Item> = [];

  constructor(someService: SomeService) {
    // let's say SomeService.getItems() returns array of {text: 'something'}
    this.items = someService.getItems();
}