Angular如何将数组传递给组件

时间:2019-07-19 05:04:47

标签: angular typescript

如何将数组从模板传递到组件文件。我有一个if条件,它取决于循环的索引。请帮助我找到正确的方法。像这样 https://jsfiddle.net/HB7LU/7638

<ul>
  <li *ngFor="let data of list_value | keyvalue; let i=index;" (click)="getListValue(i,data)">
  <li>
  <ul>
     <li *ngFor="let item of data.value" *ngIf="data[i].active">
     <li>
  <ul>
<ul>

example.componet.ts文件

export class SomeComponent{

   list_value: Array<any> = [];
   active: boolean;

   getListValue(index: String, data: any) {
       console.log("Test",data[index]);
       list_value[index].active = !list_value[index].active
   }
}

3 个答案:

答案 0 :(得分:1)

将数据传递到组件的一种方法是使用@input,例如:

<ul>
  <li *ngFor="let data of list_value | keyvalue; let i=index;" (click)="getListValue(i,data)">
  <li>
  <ul>
     <li *ngFor="let item of data.value" *ngIf="data[i].active">
      <app-selector *ngSwitchCase="'observations'" [inputdata]=item></app-selector>

     <li>

以及您的component.ts文件中,该文件加载到*ngFor内部:

import { Component, OnInit, Input, NgModule, ViewChild, ElementRef } from '@angular/core';
@Component({
  selector: 'app-selector',
  templateUrl: './selector.component.html',
  styleUrls: ['./selector.component.scss']
})
export class ObservationsComponent implements OnChanges{
  @Input() inputdata: any;
}
ngOnChanges() {
        console.log(this.inputdata)

    }

答案 1 :(得分:0)

如果要传递数组,只需传递list_value。 * ngFor就像for循环一样,它遍历数组。数据本身可能是一个数组(因为它是“ any”类型)。但是您在函数中发送的索引是数据在list_value [index]

中的索引

*ngIf="data.active"

正如在给定链接中显示的那样,您不需要索引。只需写data.active = !data.active

答案 2 :(得分:0)

希望下面的代码会有所帮助

<ul>
  <li *ngFor="let data of list_value;let i=index" (click)="getListValue(i,data)">    
      <span>{{data.name}}</span>
      <ul>

                <li *ngFor="let subItem of data.subItems" [hidden]="!data.active">
                    <span>---{{subItem.name}}</span>
                </li>
            </ul>
  </li> 
</ul>

组件ts

   export class SomeComponent{
     list_value: Array<any> = [
            {          
                name: "Item1",
                subItems: [
                    {name: "SubItem1"},
                    {name: "SubItem2"}
                ]
            },
            {
                name: "Item2",            
                subItems: [
                    {name: "SubItem3"},
                    {name: "SubItem4"},
                    {name: "SubItem5"}
                ]
            },
            {
                name: "Item3",
                subItems: [
                    {name: "SubItem6"}
                ]
            }
        ];;   
       getListValue(index: number, data: any) {      
           this.list_value[index].active = !this.list_value[index].active
       }
    }

Workign应用 https://stackblitz.com/edit/angular-gtqnmh