我尝试学习 Angular,现在我处于 @Input
阶段。
我有一个主应用程序和一个子组件。在 app.component.ts
我有一个测试变量。我想将此变量从 app.component.ts
传递到 child.component.ts
。
// app.component.ts:
export class AppComponent {
test = 10;
}
// child.component.ts:
export class ChildComponent {
@Input() fromParent: number;
childVar = fromParent + 5;
show() {
console.log(this.childVar);
} //this should to show 15 in console...
}
现在,我该怎么做呢?
最佳答案
您可以在下面找到一个示例,该示例说明了允许父组件绑定(bind)子组件可以访问的属性的机制。
Parent component template: parent.component.html
<child-component
[fromParent]="fromParent">
</child-component>
Parent component class: parent.component.ts
export class ParentComponent {
fromParent: string = 'String from parent';
}
Child component class: child.component.ts
import { Component, Input } from '@angular/core';
//...
export class ChildComponent {
@Input() fromParent: string;
}
Child component template: child.component.html
String from parent: {{ fromParent }}
关于angular - 理解@input——从 parent 到 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53666817/