Angular组件间传值

来源:互联网 发布:图像边缘检测算法代码 编辑:程序博客网 时间:2024/06/05 08:03

在Angular中,父组件调用子组件,可以传递参数,子组件根据传递过来的参数返回相应的数据;

父组件向子组件传参,过程如下:

方法一:

在子组件中:

@Component({selector: 'test-component',template: `{{inputValue}}`,inputs: ['inputsValue'] })export class TestComponent {private inputsValue;//注意,要在组建内声明,才能使用}

在父组件中:

@Component({selector: 'parent-component',template: `<test-component [inputsValue]="data"></test-component>`//以“[属性]=值”的方式传递})export class ParentComponent {  private data = 'Hello InputValue~!';}

如果不配置元数据,我们还可以在组件类中用“@Inputs() inputsValue”声明,效果一样。

方法二:

在子组件中:

import { Component, OnInit, Input } from '@angular/core';
@Component({selector: 'test-component',template: `{{inputValue}}`})export class TestComponent {@Input() name: string;//注意,要在组建内声明,才能使用}

在父组件中设置与方法一相同,此处不再赘述。

PS:@Input后面要加上(),不然没效果。


原创粉丝点击