我的目标是将字符串参数传递给组件。例如:我有保存并显示标题和副标题的组件。我想在设置选择器时传递该字符串。喜欢的东西:Angular 2传递组件的字符串参数
@Component({
selector: 'title-subtitle',
})
在HTML:
<title-subtitle title="My title" subtitle="My subtitle"></title-subtitle>
我的目标是将字符串参数传递给组件。例如:我有保存并显示标题和副标题的组件。我想在设置选择器时传递该字符串。喜欢的东西:Angular 2传递组件的字符串参数
@Component({
selector: 'title-subtitle',
})
在HTML:
<title-subtitle title="My title" subtitle="My subtitle"></title-subtitle>
父组件:
<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中属性的命名。当您实际需要对数据进行某些操作时(例如深度克隆它,...),您只需要OnInit和/或OnChanges事件。如果你只用插值法在HTML中显示它,则不需要这些事件。
注意:这是发送给您的孩子的相同的对象(相同的参考),这意味着如果您更新您的ChildComponent中的对象的属性,更改也会影响父对象。通常你克隆你的对象以避免OnInit或OnChanges事件中的那种行为。
如果您查看此Hero例如,它应该回答你的问题
注重
<my-hero-detail [hero]="selectedHero"></my-hero-detail>
在app.component.ts文件
尝试在给出答案之前阅读问题 – TeodorKolev
要使用@input传递一个字符串从父组件到子组件有两种方法。
如果你想传递的字符串,
<child-component childInput="child input"> </child-component>
如果您想从父组件的变量传递给子组件,
<child-component [childInput]="parentInput"> </child-component>
检查这个活plnk。它可能会帮助你http://plnkr.co/edit/LEtEN9?p=preview –
这正是我的答案tho:p。 具体而言,你不能只是像你想要的那样传递一个字符串参数。您可以使用Angular2的Parent to Child通信,它使用“@ Input”,您可以在其中发送带有其属性的“Object”。 –