4

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.

roopteja
  • 721
  • 2
  • 16
  • 36
  • Where are you actually using Component3? – Stephen Wilson Nov 17 '17 at 11:43
  • That is just to test whether the value is getting passed from parent component to child component. If this works I could use it somewhere else in the program – roopteja Nov 17 '17 at 11:46
  • How are you using app-my-component3 ? – marinvirdol Nov 17 '17 at 11:50
  • By tag. And this mycomponent3 i am not using anywhere in the program. I used this component to just test wether the input value is getting passed from parent component to child Component. – roopteja Nov 17 '17 at 11:52
  • 2
    Try using it like this – marinvirdol Nov 17 '17 at 11:58
  • Yess!!!!! That helped and resolved my problem. Thank You for the answer. And Could you please tell me why we have to mention that in component3 tag. – roopteja Nov 17 '17 at 12:01
  • HI. I notice your ```import``` path is ```@angular/core/src/metadata/lifecycle_hooks``` instead of ```@angular/core```, my auto imports in VSCode are doing the same thing. I wonder why this is!! ?? – Drenai Nov 18 '17 at 11:30

1 Answers1

3

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>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396