如何将按钮链接到数组中的另一个组件

时间:2017-12-07 11:02:15

标签: angular

强烈的文字 您好,我是Angular2的新手,我需要一些帮助。我正在做一个目录应用程序。我创建了一个数组(我认为它是一个),但是我需要将数组中的每个项目链接到另一个组件。我打算在每个项目的Typescript文件中有一个链接,然后HTML文件中的按钮将调用它。但是,我不知道该怎么做。

打字稿文件:

export class NikeComponent implements OnInit {
 title = 'Nike Catalgoue';
  
  nikeShirts =  [ {
	  "id": 1,
	  "name": "Nike SB x Medicom Dry",
	  "description": "Men's T-Shirt",
	  "inStock": "$49",
      "image": "../assets/nike_shirt_1.jpg",
   
  },
{
	  "id": 2,
	  "name": "NikeLab ACG",
	  "description": "Men's T-Shirt",
	  "inStock": "$109",
     "image": "../assets/nike_shirt_2.jpg"
 },
{
	  "id": 3,
	  "name": "Nike Futura Icon",
	  "description": "Men's T-Shirt",
	  "inStock": "$42",
     "image": "../assets/adidas_shirt_3.jpg"
},
{
    "id": 4,
	  "name": "Nike SB x Medicom Dry",
	  "description": "Men's T-Shirt",
	  "inStock": "$49",
      "image": "../assets/nike_shirt_1.jpg",
  
  },
{
	  "id": 5 ,
	  "name": "NikeLab ACG",
	  "description": "Men's T-Shirt",
	  "inStock": "$109",
     "image": "../assets/nike_shirt_2.jpg"
 },
{
	  "id": 6,
	  "name": "Nike Futura Icon",
	  "description": "Men's T-Shirt",
	  "inStock": "$42",
     "image": "../assets/nike_shirt_3.jpg"
}];

HTML文件:

<li *ngFor = "let nikeShirt of nikeShirts">
  <img src ={{nikeShirt.image}} height="200" width="250" />
  <h2> {{nikeShirt.name}} </h2>
	<p> <i>{{nikeShirt.description}}</i> </p>
	<p> {{nikeShirt.inStock}} </p>
   <button href="/home" class="btn">Review</button>
</li>
</ul>

1 个答案:

答案 0 :(得分:0)

如果您打算实际导航到另一个地方,您可以在数组的每个元素上创建一个名为url或source或类似内容的属性

{
  "id": 1,
  "name": "Nike SB x Medicom Dry",
  "description": "Men's T-Shirt",
  "inStock": "$49",
  "image": "../assets/nike_shirt_1.jpg",
  “url”: “<your url here>”

}

然后在html上你可以有像

这样的东西
<li *ngFor = "let nikeShirt of nikeShirts">
  <img src ={{nikeShirt.image}} height="200" width="250" />
  <h2> {{nikeShirt.name}} </h2>
<p> <i>{{nikeShirt.description}}</i> </p>
<p> {{nikeShirt.inStock}} </p>
  <a href=“{{nikeShirt.url}}” </a>
   <button href="/home" class="btn">Review</button>
</li>

顺便说一句,你的按钮Review不起作用,因为按钮没有href。它们并不意味着通常不会导航。它们用于触发行动。

您可以通过将其转换为<a href="/home" class="btn">Review</a>并使用某些css

进行样式来获得所需的结果