如何将索引传递给组件角度2

时间:2017-10-17 15:19:58

标签: angular

不重复。我完成了我的研究。如果您仍然觉得,这不是一个好问题,请在评论中写下答案并删除问题。我想做什么我将index的值从HTML元素传递给组件。

<ul *ngFor="let person of persons; let i= index" [index]="i">

//上面^^^^^视图的组件

class appComponent{
@Input() index; // this should get the value of index; but it gives undefined
}

4 个答案:

答案 0 :(得分:3)

您不能在同一个组件

上使用 @Input

你可以这样做

<div *ngFor="let person of persons;let i = index">
    <div (click)="getIndex(i)">
    </div>
<div>`

然后在TS

getIndex(index){
   console.log(index);//clicked index
}

答案 1 :(得分:0)

当您在 ul 中执行 [index] = 时,模板会尝试将此索引中的值添加到ul tagm中名为“index”的属性中,但是这样财产不存在。 您可以将此值绑定到另一个属性,例如data- * attribute:

<ul [attr.data-index]="index">

当你说'我想要做的时候,我将索引的值从HTML元素传递给组件'时,这没有意义:你不能将数据传递给html元素(它们不是角度组件)。但是,正如我所说,yu可以“存储”房产中的价值。

答案 2 :(得分:0)

根据我的理解,您的要求是将i的最后一个值赋给组件变量。基本上这是persons数组的长度。您只需使用方法this.input=this.persons.length;

仅当您将父组件中的值传递给子组件时,才必须使用

@Input()。 例如:

//parent component class:

@Component({
 selector:'parent-component',
 template: `<child-component [inputVariable]='parentVariable'>`
})

export class ParentComponent{
 parentVariable='foo';
}

//the child component class:

@Component({
selector:'child-component',
template:`<div>{{inputVariable}}<div>`
})
export class ChildComponent{

  @Input()
  inputVariable:any;

}

答案 3 :(得分:0)

根据您的评论:

  

我想根据悬停上的索引更改样式

我建议做以下事情。首先,在<li>上移动* ngFor,然后设置(mouseover)和(mouseout)事件以跟踪哪个li悬停。另外,如果需要,使用ngStyle(我添加事件/对行着色以防万一):

<ul>
  <li *ngFor="let person of persons; let i= index; let even = even" 
      (mouseover)="hovered = i" (mouseout) = "hovered = -1" 
      [ngStyle] = "{'background-color': hovered === i ? 'red' : even ? 'yellow' : 'blue'}">
    {{person.name}}
  </li>
</ul>

<强> DEMO

相关问题