【问题标题】:Angular4 @Input() to pass value from parent component to child componentAngular4 @Input() 将值从父组件传递给子组件
【发布时间】:2018-05-01 04:25:50
【问题描述】:

我在 App component.html 中有这样的代码。

 <form>
        <input #box1 (blur)="onKey1(box1.value)" type="text" name="username">
        <p>{{box1.value}}</p>
    </form>

在 AppComponent.ts 我有这样的代码。

import { Component } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent{
    type:string;
    constructor() { }
    onKey1(value:string)
    {
        this.type=value;  
    }
}

现在我创建了一个名为 MyComponent3 的组件。在该组件中,我想从应用组件中检索数据。MyComponent3.html 的代码如下:

<p>{{type}}</p>

在 MyComponent3.ts 我有以下代码。

import { Component, OnInit, ViewEncapsulation,Input } from '@angular/core';
@Component({
    selector: 'app-my-component3',
    templateUrl: './my-component3.component.html',
    styleUrls: ['./my-component3.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class MyComponent3Component implements OnInit {
    @Input() type;
    ngOnInit() {
    }
}

但在输出中,值没有从 AppComponent 传递到 My Component3。

【问题讨论】:

  • 您实际在哪里使用 Component3?
  • 这只是为了测试值是否从父组件传递到子组件。如果这可行,我可以在程序的其他地方使用它
  • 你是如何使用 app-my-component3 的?
  • 通过 标签。这个 mycomponent3 我没有在程序中的任何地方使用。我使用这个组件来测试输入值是否从父组件传递到子组件。
  • 尝试像这样使用它

标签: angular


【解决方案1】:

你想传递给子组件的任何属性都应该在里面提到。您可以使用@input 和html 传递给子组件,如下所示,

<app-my-component3 [type]="type"></app-my-component3>

【讨论】:

猜你喜欢
  • 2020-02-04
  • 2018-02-15
  • 2019-06-15
  • 2017-05-19
  • 2019-08-25
  • 2016-12-16
  • 2019-02-17
  • 2020-08-21
  • 1970-01-01
相关资源
最近更新 更多