-
StackOverflow 文件
-
Angular 教程
-
在元件之間共享資料
-
通過共享服務將資料從父元件傳送到子元件
service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class AppState {
public mylist = [];
}
parent.component.ts:
import {Component} from '@angular/core';
import { AppState } from './shared.service';
@Component({
selector: 'parent-example',
templateUrl: 'parent.component.html',
})
export class ParentComponent {
mylistFromParent = [];
constructor(private appState: AppState){
this.appState.mylist;
}
add() {
this.appState.mylist.push({"itemName":"Something"});
}
}
parent.component.html:
<p> Parent </p>
<button (click)="add()">Add</button>
<div>
<child-component></child-component>
</div>
child.component.ts:
import {Component, Input } from '@angular/core';
import { AppState } from './shared.service';
@Component({
selector: 'child-component',
template: `
<h3>Child powered by shared service</h3>
{{mylist | json}}
`,
})
export class ChildComponent {
mylist: any;
constructor(private appState: AppState){
this.mylist = this.appState.mylist;
}
}