将数据从一个组件传递到另一个组件并在视图中反映出来 [英] Pass data from one component to another and reflect in view
本文介绍了将数据从一个组件传递到另一个组件并在视图中反映出来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的项目中,我有两个组成部分
In my project i have two components
component1.ts
import { Component, OnInit } from '@angular/core';
import { MyserviceService } from '../myservice.service';
@Component({
selector: 'app-component1',
templateUrl: './component1.component.html',
styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {
constructor(private Service: MyserviceService) { }
employee = [
{ id: '001', name: 'michael' },
{ id: '002', name: 'john' },
{ id: '003', name: 'james' },
{ id: '004', name: 'joe' },
];
ngOnInit() {
}
onSelect(name) {
alert(name);
this.Service.setValue(name);
}
}
html
<div *ngFor="let emp of employee" (click)="onSelect(emp.name)">
Id: {{emp.id}} <br />
Name: {{emp.name}}
</div>
在这里,onclick emp.name通过onselect()传递给服务
Here onclick emp.name is passed to a service via onselect()
我需要将此值传递给第二个组件
i need this value to be passed to a second component
component2.ts
component2.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-component2',
templateUrl: './component2.component.html',
styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {
private selectedName: string;
constructor() { }
ngOnInit() {
}
}
html
<p>
selected name is: {{selectedName}}
</p>
服务代码为:
import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
private myValue;
constructor() { }
setValue(val) {
this.myValue = val;
}
getValue() {
return this.myValue;
}
}
我需要在component2 html代码中将名称显示为变量selectedName.
i need to display name in component2 html code as variable selectedName.
推荐答案
最好使用可观察对象主动通知订户价值变化:
It's best to use an observable to actively notify subscribers about value changes:
@Injectable()
export class MyserviceService {
private myValue = new BehaviorSubject<String>(null);
public myValue$ = this.myValue.asObservable();
}
export class Component2Component implements OnInit {
private selectedName: string;
constructor(service:MyserviceService) {
this.service.myValue$.subscribe(val => this.selectedName = val);
}
}
这篇关于将数据从一个组件传递到另一个组件并在视图中反映出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文