简体   繁体   中英

Angular4 @Input() to pass value from parent component to child component

I have a code in App component.html like this.

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

In AppComponent.ts I have code like this.

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;  
    }
}

Now I have created a component named MyComponent3. In that component I want to retrieve the data from app component.The code for MyComponent3.html is as follows:

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

In MyComponent3.ts I have the following code.

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() {
    }
}

But in the Output the value is not getting passed from AppComponent to My Component3.

Whatever attribute you want to pass to child component should be mentioned in it. You can pass to the child component using @input and the html as follows,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM