简体   繁体   English

如何在Angular 2中将对象从一个组件传递到另一个组件?

[英]How to pass object from one component to another in Angular 2?

I have Angular components and first component uses the second one as a directive . 我有Angular组件 ,第一个组件使用第二个组件作为指令 They should share the same model object , which is initialized in the first component. 它们应该共享相同的模型对象 ,该对象在第一个组件中初始化。 How can I pass that model to the second component? 如何将该模型传递给第二个组件?

For one-way data binding from parent to child, use the @Input decorator (as recommended by the style guide) to specify an input property on the child component 对于从父级到子级的单向数据绑定,使用@Input装饰器(根据样式指南的建议 )在子组件上指定输入属性

@Input() model: any;   // instead of any, specify your type

and use template property binding in the parent template 并在父模板中使用模板属性绑定

<child [model]="parentModel"></child>

Since you are passing an object (a JavaScript reference type) any changes you make to object properties in the parent or the child component will be reflected in the other component, since both components have a reference to the same object. 由于传递对象(JavaScript引用类型),因此对父组件或子组件中的对象属性所做的任何更改都将反映在另一个组件中,因为两个组件都引用了同一对象。 I show this in the Plunker . 我在Plunker中展示了这一点

If you reassign the object in the parent component 如果重新分配父组件中的对象

this.model = someNewModel;

Angular will propagate the new object reference to the child component (automatically, as part of change detection). Angular会将新对象引用传播到子组件(作为更改检测的一部分自动传播)。

The only thing you shouldn't do is reassign the object in the child component. 您不应该做的唯一事情是重新分配子组件中的对象。 If you do this, the parent will still reference the original object. 如果这样做,父级仍将引用原始对象。 (If you do need two-way data binding, see https://stackoverflow.com/a/34616530/215945 ). (如果确实需要双向数据绑定,请参阅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 Plunker - Angular RC.2

Component 2, the directive component can define a input property ( @input annotation in Typescript). 组件2,指令组件可以定义输入属性(Typescript中的@input注释)。 And Component 1 can pass that property to the directive component from template. 组件1可以将该属性从模板传递给指令组件。

See this SO answer How to do inter communication between a master and detail component in Angular2? 请参阅此SO答案如何在Angular2中的主组件和详细信息组件之间进行相互通信?

and how input is being passed to child components. 以及如何将输入传递给子组件。 In your case it is directive. 在你的情况下它是指令。

you could also store your data in an service with an setter and get it over a getter 您还可以将数据存储在带有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;
    }
}

Use the output annotation 使用输出注释

@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);

From component 来自组件

 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 DataService的

 import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable() export class dataService { refLWTableColumnNames: object;//creating an object for the data } 

To Component 到组件

 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.

相关问题 如何将对象从一个组件传递到另一个组件 - how can I pass an object from one component to another in angular 如何在Angular中将对象从一个组件传递到另一个组件 - How to pass an object from one Component to another in Angular 如何将json对象的一个​​组件传递给angular中的另一个组件? - How to pass json object one component to another component in angular? 如何以角度从另一个组件传递对象? - How can i pass object one component from another component in angular? 如何在单击按钮时将 id 和对象从一个组件传递到另一个组件的 angular 函数? - How do I pass an id and object on click of a button from one component to another component' s function in angular? Angular 4 - 将对象从一个组件传递到另一个组件(没有父 - 子层次结构) - Angular 4 - Pass an object from one component to another (no parent - child hierarchy) 无法在 angular 2 中将响应 object 从一个组件传递到另一个组件 - Unable to pass response object from one component to another in angular 2 如何将角度2中的数据从一个组件传递到另一个组件? - how to pass data from one component to another component in angular 2? 如何在Angular2中将值从一个组件传递到另一个组件? - How to pass value from one component to another component in Angular2? 如何将对象从一个组件传递到另一个组件以在angular2中建立数据模型? - how to pass an object from one component to another to build a data model in angular2?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM