在我的项目中,我有两个组件
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()
传递给服务我需要将此值传递给第二个组件
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代码中将name显示为变量selectedName。
答案 0 :(得分:0)
最好使用observable主动通知订阅者有关价值变化的信息:
@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);
}
}
答案 1 :(得分:0)
Angular文档讨论了如何使用@Input绑定 [https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child][1]
在您的组件中1 html格式id和方括号内的名称以及替换div标签,其名称为组件2选择器标记
<app-component2 *ngFor="let emp of employee" (click)="onSelect(emp.name)"
[hero]="hero"
[master]="master">
</app-component2>
在组件2 .ts文件中添加导入和输入变量
import { Component, Input } from '@angular/core';
export class Component2Component {
@Input() Id: string;
@Input() Name: string;
}
在你的组件2 html中
<p>
selected name is: {{Name}}
</p>