Search code examples
angulartypescriptproperty-binding

Angular: bracket syntax doesn't work when providing input values?


Using bracket syntax to provide input value doesn't work. However, when I remove the brackets, its does. Why is this?

Child component:

@Component({
  selector: 'app-child',
  template: `<p>My name is {{name}}</p>`,
})
export class ChildComponent  {
  @Input() name;
}

Parent component template - this doesn't work, why??:

<p>Parent component</p>

<app-child [name]='Peter'></app-child>

Parent component template - this work's:

<p>Parent component</p>

<app-child name='Peter'></app-child>

Solution

  • Parent component template - this doesn't work, why??:

    Parent component

    <app-child [name]='Peter'></app-child>

    Here, angular looks for a variable named Peter which doesn't exist. If you change it to

    <app-child [name]="'Peter'"></app-child>
    

    it will work as expected.

    Also, from the Angular docs:

    You should omit the brackets when all of the following are true:

    1. The target property accepts a string value.

    2. The string is a fixed value that you can put directly into the template.

    3. This initial value never changes.