angular - 将数据从一个组件传递到另一个组件并反射(reflect)在 View 中

标签 angular typescript visual-studio-code

在我的项目中我有两个组件

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/

相关文章:

angular - 从 App 组件中隐藏 header 组件

javascript - 如何将 ngClass 仅应用于一个表头

node.js - 如何使用node sdk在azure函数中初始化cosmosDB数据库和容器?

visual-studio-code - 如何在 vs code 中仅缩小终端?

TypeScript AST 转换删除所有空行

android-studio - Flutter Doctor 发现问题 Android_Home

node.js - 如何在 proxy.conf.json 或 proxy.conf.js 中动态定义端口

angular - 在 Angular 5 中使用基本授权保存图像

angular - 如何使用http.post发送图像

javascript - VS Code 能否在文件重命名/移动时自动更新 JavaScript 和 TypeScript 导入路径?