繁体   English   中英

Angular 2 将变量从一个组件传递到另一个组件

[英]Angular 2 pass variable from one component to another

所以我有一个包含列表数组的组件:

一个组件 TS :

list = [
{name:Jhon},
{name: Pop}
]

一个组件 html :

<h2>List :</h2>
<b-component></b-component> //how to pass list to B component here ?

B 组件 html :

<div *ngFor="let item of list">
{{list.name}}
</div>

如何将 A 组件列表传递给标签上的 B 组件?

看到这个stackblitz 演示

父组件

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <hello [list]="list"></hello>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  list = ['abc', 'edf', 'ghi'];
}

子组件

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
  <ul>
    <li *ngFor="let item of list">
      {{item}}
    </li>
  </ul>
  `
})
export class HelloComponent {
  @Input() list: string[];
}

在你的B 组件 .ts 文件中,你必须像这样定义你的列表:

@Input() list;

有了这个,您可以使用B 组件 html 中的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM