首页 > 解决方案 > Angular如何将数组传递给组件

问题描述

如何将数组从模板传递到组件文件。我有一个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
   }
}

标签: angulartypescript

解决方案


将数据传递给组件的一种方法是@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)

    }

推荐阅读