[英]How to pass object from one component to another in Angular 2?
我有Angular組件 ,第一個組件使用第二個組件作為指令 。 它們應該共享相同的模型對象 ,該對象在第一個組件中初始化。 如何將該模型傳遞給第二個組件?
對於從父級到子級的單向數據綁定,使用@Input
裝飾器(根據樣式指南的建議 )在子組件上指定輸入屬性
@Input() model: any; // instead of any, specify your type
並在父模板中使用模板屬性綁定
<child [model]="parentModel"></child>
由於傳遞對象(JavaScript引用類型),因此對父組件或子組件中的對象屬性所做的任何更改都將反映在另一個組件中,因為兩個組件都引用了同一對象。 我在Plunker中展示了這一點 。
如果重新分配父組件中的對象
this.model = someNewModel;
Angular會將新對象引用傳播到子組件(作為更改檢測的一部分自動傳播)。
您不應該做的唯一事情是重新分配子組件中的對象。 如果這樣做,父級仍將引用原始對象。 (如果確實需要雙向數據綁定,請參閱https://stackoverflow.com/a/34616530/215945 )。
@Component({
selector: 'child',
template: `<h3>child</h3>
<div>{{model.prop1}}</div>
<button (click)="updateModel()">update model</button>`
})
class Child {
@Input() model: any; // instead of any, specify your type
updateModel() {
this.model.prop1 += ' child';
}
}
@Component({
selector: 'my-app',
directives: [Child],
template: `
<h3>Parent</h3>
<div>{{parentModel.prop1}}</div>
<button (click)="updateModel()">update model</button>
<child [model]="parentModel"></child>`
})
export class AppComponent {
parentModel = { prop1: '1st prop', prop2: '2nd prop' };
constructor() {}
updateModel() { this.parentModel.prop1 += ' parent'; }
}
Plunker - Angular RC.2
組件2,指令組件可以定義輸入屬性(Typescript中的@input
注釋)。 組件1可以將該屬性從模板傳遞給指令組件。
請參閱此SO答案如何在Angular2中的主組件和詳細信息組件之間進行相互通信?
以及如何將輸入傳遞給子組件。 在你的情況下它是指令。
您還可以將數據存儲在帶有setter的服務中,並通過getter獲取
import { Injectable } from '@angular/core';
@Injectable()
export class StorageService {
public scope: Array<any> | boolean = false;
constructor() {
}
public getScope(): Array<any> | boolean {
return this.scope;
}
public setScope(scope: any): void {
this.scope = scope;
}
}
使用輸出注釋
@Directive({
selector: 'interval-dir',
})
class IntervalDir {
@Output() everySecond = new EventEmitter();
@Output('everyFiveSeconds') five5Secs = new EventEmitter();
constructor() {
setInterval(() => this.everySecond.emit("event"), 1000);
setInterval(() => this.five5Secs.emit("event"), 5000);
}
}
@Component({
selector: 'app',
template: `
<interval-dir (everySecond)="everySecond()" (everyFiveSeconds)="everyFiveSeconds()">
</interval-dir>
`,
directives: [IntervalDir]
})
class App {
everySecond() { console.log('second'); }
everyFiveSeconds() { console.log('five seconds'); }
}
bootstrap(App);
來自組件
import { Component, OnInit, ViewChild} from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { dataService } from "src/app/service/data.service"; @Component( { selector: 'app-sideWidget', templateUrl: './sideWidget.html', styleUrls: ['./linked-widget.component.css'] } ) export class sideWidget{ TableColumnNames: object[]; SelectedtableName: string = "patient"; constructor( private LWTableColumnNames: dataService ) { } ngOnInit() { this.http.post( 'getColumns', this.SelectedtableName ) .subscribe( ( data: object[] ) => { this.TableColumnNames = data; this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service } ); } }
DataService的
import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable() export class dataService { refLWTableColumnNames: object;//creating an object for the data }
到組件
import { Component, OnInit } from '@angular/core'; import { dataService } from "src/app/service/data.service"; @Component( { selector: 'app-linked-widget', templateUrl: './linked-widget.component.html', styleUrls: ['./linked-widget.component.css'] } ) export class LinkedWidgetComponent implements OnInit { constructor(private LWTableColumnNames: dataService) { } ngOnInit() { console.log(this.LWTableColumnNames.refLWTableColumnNames); } createTable(){ console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.