typescript 从父组件到子组件的角度传递数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45171832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular passing array from parent to child component
提问by Alistair Hardy
Before we start, I started learning Angular about 1 week ago, don't be afraid to take it right back to basics.
在我们开始之前,我大约 1 周前开始学习 Angular,不要害怕把它带回基础。
So how do you do it? In app.component.ts I have an standard array that needs to be accessable by multiple child components.
你是怎么做到的?在 app.component.ts 中,我有一个标准数组,需要多个子组件访问它。
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
masterArray = ['Create', 'Foo', 'Bar'];
}
How do pull this into child components generated by angular cli. For example I need to use it in the navigation component to generate the navigation panel.
如何将其拉入 angular cli 生成的子组件中。例如我需要在导航组件中使用它来生成导航面板。
<li *ngFor = "let i of masterArray; let ind = index">
<a>{{i}}</a>
</li>
回答by subaru710
You can make the array as input of children components.
您可以将数组作为子组件的输入。
@Component({
selector: 'app-navigation',
templateUrl: './navi.component.html',
styleUrls: ['./navi.component.css']
})
export class NavigationComponent {
@Input() masterArray : string[];
}
And pass the array to child component in html of parent component.
并将数组传递给父组件html中的子组件。
<app-navigation [masterArray]="masterArray"></app-navigation>
回答by DeborahK
If the data needs to be accessed by multiple child components, you may want to instead create a service. The service can then hold the array and anycomponent can access it.
如果数据需要被多个子组件访问,您可能需要创建一个服务。然后服务可以保存数组并且任何组件都可以访问它。
I have a simple example here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
我这里有一个简单的例子: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'];
}
Then you access that data like this:
然后您可以像这样访问该数据:
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) { }
}