Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@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;
like image 298
Ramya Avatar asked Dec 14 '22 21:12

Ramya


2 Answers

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.

like image 146
Plog Avatar answered Dec 16 '22 22:12

Plog


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);
    }
}
like image 33
Rohan Fating Avatar answered Dec 16 '22 23:12

Rohan Fating