在我的项目中我有两个组件
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() 传递给服务
我需要将这个值传递给第二个组件
组件2.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 文档谈论使用@Input 绑定(bind) [ https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child][1]
在您的组件 1 html 格式中,方括号内的 id 和名称以及用组件 2 选择器标签的名称替换 div 标签
<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>
关于angular - 将数据从一个组件传递到另一个组件并反射(reflect)在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42385142/