0

Why is the input binding not working? I have taken the framework code created by IntelliJ and have replaced the default app component with my component my-para. Following is the code snippet.

index.html

<body>
  <my-para [paratext]="say something"></my-para>
</body>

paragraph.component.ts

import {Component, Input } from "@angular/core";

@Component({
  selector: 'my-para',
  inputs: ['paratext'],
  template:`
    <p>Hello {{this.paratext}}</p>
  `
})

export class MyParaComponent {
   @Input() paratext: string;   
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {MyParaComponent} from './paragraph.component'

@NgModule({
  declarations: [
    MyParaComponent,
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [MyParaComponent]
})
export class AppModule { }

I see only "hello" but not "hello say something"

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
  • ``. That "say something" part needs to be a string. But there are a lot of redundant lines in your code. Please follow the official documentation: https://angular.io/tutorial – eko Jun 22 '17 at 07:33
  • sorry, didnt work – Manu Chadha Jun 22 '17 at 07:35

2 Answers2

1

If you use square brackets, it tries to bind an object. So <my-para [paratext]="say something"></my-para> code looks for "say something" attribute.

Just pass your string without brackets.

<my-para paratext="say something"></my-para>

Also another node,

In your index.html there should be an app component only. Use it inside your app.component.html <my-para paratext="say something"></my-para>

Inside your MyParaComponent component, just use @Input() decorator not inputs attribute of Component. You are defining your inputs twice.

Bunyamin Coskuner
  • 8,719
  • 1
  • 28
  • 48
  • didn't understand what you mean by defining the input twice? Wouldn't there be a name clash if the variable was getting defined twice? – Manu Chadha Jun 22 '17 at 12:50
0

Got help from following SO answer (some points were mentioned by you guys as well)

Angular 2 Component @Input not working

It seems I cannot pass input in root component. Explanation is here - Angular 2 input parameters on root directive

I created AppComponent. Then in AppComponent's template, I used MyParaComponent

index.html

<body>
  <app-root></app-root>
</body>

app.component.ts

@Component({
  selector: 'app-root',
  template: `<my-para [paratext]="'say something'"></my-para>`
})
export class AppComponent {
}

app.module.ts - had to add both AppComponent and MyParaComponent in declarations

declarations: [
    AppComponent,
    MyParaComponent
  ],
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184