【问题标题】:Angular passing array from parent to child component从父组件到子组件的角度传递数组
【发布时间】:2023-04-09 05:49:01
【问题描述】:

在我们开始之前,我大约 1 周前开始学习 Angular,不要害怕回到基础。

那么你是怎么做到的呢? 在 app.component.ts 我有一个标准数组,需要多个子组件访问。

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  masterArray = ['Create', 'Foo', 'Bar'];
}

如何将其拉入由 angular cli 生成的子组件中。 比如我需要在导航组件中使用它来生成导航面板。

<li *ngFor = "let i of masterArray; let ind = index">
  <a>{{i}}</a>
</li>

【问题讨论】:

  • 我的建议:每当您有问题时,请在 SO 中创建内容之前搜索并阅读更多内容。这是一个非常基础的话题,像你一样直接问在我看来缺乏研究能力
  • 我一直在谷歌搜索并阅读了关于 SO 的多个线程,甚至是你自己链接的那个。但是我要么无法让他们工作,要么他们与我正在做的事情无关

标签: angular typescript angular-cli


【解决方案1】:

您可以将数组作为子组件的输入。

@Component({
  selector: 'app-navigation',
  templateUrl: './navi.component.html',
  styleUrls: ['./navi.component.css']
})
export class NavigationComponent {
  @Input() masterArray : string[];
}

并将数组传递给父组件的html中的子组件。

<app-navigation [masterArray]="masterArray"></app-navigation>

【讨论】:

  • 谢谢!我也是 Angular 的新手。 HTML 是我在其他所有答案中所缺少的。
【解决方案2】:

如果数据需要被多个子组件访问,您可能需要创建一个服务。然后服务可以保存该数组,任何组件都可以访问它。

我这里有一个简单的例子:https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

import { Injectable } from '@angular/core';

@Injectable() 
export class DataService {
  masterArray = ['Create', 'Foo', 'Bar']; 
}

然后你像这样访问这些数据:

import {Component} from '@angular/core';
import { DataService } from './data.service';

@Component({
   selector: 'app-navigation',
   templateUrl: './navi.component.html',
   styleUrls: ['./navi.component.css']
 })
 export class NavigationComponent {

 get masterArray() { 
    return this.dataService.masterArray; 
 } 

 constructor(public dataService: DataService) { } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2019-01-04
    相关资源
    最近更新 更多