Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Input() in Angular2 does not work with string

Tags:

angular

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 ?

like image 699
NBM Avatar asked Feb 06 '23 08:02

NBM


1 Answers

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.

like image 85
Günter Zöchbauer Avatar answered Feb 08 '23 16:02

Günter Zöchbauer