【发布时间】:2017-07-12 03:03:52
【问题描述】:
在我的项目中,我有两个组件
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 代码中将名称显示为变量 selectedName。
【问题讨论】:
标签: angular typescript visual-studio-code