7

Please see below codes :

import { AppComponent } from './app.component';
import { HelloWorldComponent } from './hello-world/hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I added 'HelloWorldComponent' to main component ('AppComponent')

in 'app.component.html'

<h1>
  {{title}}
  <app-hello-world [name]="test"></app-hello-world> // When [name]="Test" does not works but when I use number works !!! [name] = "4"
</h1>

in 'hello-world.component.ts' in used @Input() decorator

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

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent implements OnInit {
  @Input() name: string;
  constructor() { }

  ngOnInit() {
  }

}

and in 'hello-world.component.html'

<p>
{{name}}
</p>

Why when I passa string to [name] it does not work ?

2 Answers 2

15

What you want is

[name]="'test'"

or

name="test"

because without quotes test is interpreted as identifier, while 5 isn't (like in normal TS code)

The difference between the two variants is that
the former does property binding and won't show up in the DOM
while the second is a normal HTML attribute that is also read by Angular. It will be added to the DOM as is.

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

2 Comments

the needed quotes are because of Typescript or Angular2 ?
When you add [] Angular interprets the value as expression and test (without quotes) in TS/JS means the value of the variable test. [name]="test" (again without quotes) means pass the name of the field test of the components class to the name property of the HelloWorldComponent component.
0

If you are not referencing any logic that is to be evaluated, you do not need the pointy brackets around the Input() parameter. Just write

name="test"

2 Comments

Can you explan more about 'not referencing any logic' ?
What Günther wrote in the other answer. If you add the pointy brackets, you make Angular2 evaluate any expresseion (=logic) inside the quotes.

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.