1

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"

2
  • <my-para [paratext]=" 'say something' "></my-para>. 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: angular.io/tutorial Commented Jun 22, 2017 at 7:33
  • sorry, didnt work Commented Jun 22, 2017 at 7:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?
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
  ],

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.