Ramya
Ramya

Reputation: 133

@Input in Angular 4

I am new to Angular 4.As per my understanding, @Input is used to pass values to a component. But when I use it as mentioned below it doesn't work.

my-file.component.html
    <h1 [user] = "currentuser"></h1>

my-file.component.ts
    @Input() 
    user : string;

Upvotes: 4

Views: 29578

Answers (5)

Kishore Thangapandi
Kishore Thangapandi

Reputation: 229

Your understanding itself is wrong . @Input() property is used for import data from another component. Eg: That another component you can export also otherwise it will not work.

Upvotes: 0

Volodymyr Khmil
Volodymyr Khmil

Reputation: 1244

In your app.component.html

<my-file [user]="currentUser"></my-file>

In your my-file.component.ts

import {Input} from '@angular/core';

@Input() user;

After that you can use currentUser from app.component in the my-file.component

Upvotes: 0

Naresh Singh
Naresh Singh

Reputation: 19

@Input() is used to import data from another component

Example get data in a-component.ts from b-component.ts
---------------------------------

receving data in user varibale :
a-component.ts
import { Component, Input } from '@angular/core';
@Input() user;



b-component.html
<my-file [user]="anyValue"></my-file>

or 

if you are repeating a loop :
<my-file @ngFor="let item of items" [user]="item"></my-file>

Upvotes: 2

Rohan Fating
Rohan Fating

Reputation: 2133

In Component TS file you need to define <my-file-comp [user]="currentUser"></my-file-comp>

my-file.component.ts
    public @Input() currentuser: string

@Component({
  selector : 'my-file-comp',
  template: `Test Value : {{user}}`
})
class MyFileComp{
   public @Input() user: string

}

@Component({
    selector: 'testcmp',
    template : `<my-file-comp [user]="currentUser"></my-file-comp>`,
})

class TestComp{
    currentUser: string = "I Am user"; // Need to pass variable from here to my file component inside it's template
    ngOnInit() {
        console.log('This if the value for user-id: ' + this.test);
    }
}

Upvotes: 5

Plog
Plog

Reputation: 9622

It means you can pass the string input into your my-file component itself not any HTML element (i.e. h1 in your case) within the component itself.

i.e. in the parent component you can call something like:

<my-file [user]="currentuser"></my-file>

Then this value of user will be available to be used within your my-file child component.

Upvotes: 5

Related Questions