Angular 2将字符串参数传递给组件

时间:2017-01-16 13:55:10

标签: angular typescript components

我的目标是将字符串参数传递给组件。示例:我有持有并显示标题和副标题的组件。我想在设置选择器时传递该字符串。类似的东西:

@Component({
    selector: 'title-subtitle',
})

in html:

<title-subtitle title="My title" subtitle="My subtitle"></title-subtitle>

3 个答案:

答案 0 :(得分:3)

父组件:

<title-subtitle [childInput]="parentInput">
</title-subtitle>

private parentInput: any;
ngOnInit() {
    this.parentInput = 'Hello World';
}

子组件:

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

export class ChildComponent implements OnChanges, OnInit {
  @Input() private childInput: any;

  ngOnInit() {
    // When the data is passed instantly, you can access it here.
    // You can also use {{childInput}} in your HTML
    console.log(this.childInput);
  }

  ngOnChanges(changes) {
    // When the data is async : get the changes when they are ready

    // Get @Input data when it's ready
    if (changes.childInput) {      
       console.log(changes.childInput.currentValue);
    }
  }
}

请注意父HTML中属性的命名。

N.B:当您确实需要对数据执行某些操作时,您只需要OnInit和/或OnChanges事件(即深度克隆它,...)。如果您只使用插值在HTML中显示它,则不需要事件。

注意2:请注意,这是发送给您孩子的 SAME OBJECT (相同参考),这意味着如果您在ChildComponent中更新对象的属性,则更改将也会影响父母。通常,您可以克隆对象以避免在OnInit或OnChanges事件中出现这种行为。

答案 1 :(得分:3)

要使用@input从父组件向子组件传递字符串,有两种方法。

如果你想传递字符串,

<child-component childInput="child input"> </child-component>

如果要将变量从父组件传递到子组件,

<child-component [childInput]="parentInput"> </child-component>

答案 2 :(得分:0)

如果您查看此Hero示例,则应该回答您的问题

注意

<my-hero-detail [hero]="selectedHero"></my-hero-detail>
app.component.ts 文件

上的

相关问题