[英]Angular passing array from parent to child component
在我们开始之前,我在大约一周前开始学习Angular,不要害怕把它恢复到基础。
你是怎么做到的? 在app.component.ts中,我有一个标准数组,需要多个子组件可访问。
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
masterArray = ['Create', 'Foo', 'Bar'];
}
如何将其拉入由角度cli生成的子组件中。 例如,我需要在导航组件中使用它来生成导航面板。
<li *ngFor = "let i of masterArray; let ind = index">
<a>{{i}}</a>
</li>
您可以将数组作为子组件的输入。
@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>
如果数据需要由多个子组件访问,您可能希望改为创建服务。 然后,该服务可以保存阵列, 任何组件都可以访问它。
我在这里有一个简单的例子: 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) { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.