angular - 理解@input——从 parent 到 child

标签 angular typescript input angular7 angular8

我尝试学习 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/

相关文章:

javascript - 停止 SVG 组事件传播

javascript - 如何检索输入元素及其包围的跨度?

javascript - jQuery 在将表单填充到所有必填字段(如果为空)时添加类红色边框(填充除外)

java双输入面板

javascript - Material Angular 表不包含对象的排序列

angular - 以编程方式选择 Material 自动完成中的项目

css - NG-ZORRO nz卡体内对准

javascript - 我可以在没有 Nodejs 的情况下使用 Angularjs2 (ES6) 吗?

javascript - 如何获取所有 Slide-Toggle 元素的 ID 和 Value

javascript - 生成的 typescript 看起来是多余的,但我敢打赌它不是