Search code examples
angularbindingproperty-binding

Why do we need to bind to SRC to get an image from the TypeScript file?


I got an array to which I store name and some other String properties.

I also have the "ImagePath". The solution I found was that in the image source we use square brackets [ ] around the source.

I do know that it means property binding, but why do we use it around the src. What is the best way to understand property, besides this use case.

Export class RecipeListComponent implements OnInit {
  recipes: Recipe[] = [
    new Recipe('A Test Recipe', 'This is simply a test', 'https://upload.wikimedia.org/wikipedia/commons/1/15/Recipe_logo.jpeg'),
    new Recipe('A Test Recipe', 'This is simply a test', 'https://upload.wikimedia.org/wikipedia/commons/1/15/Recipe_logo.jpeg')
  ];

 <span class="float-right">
   <img [src] ="recipe.imagePath" 
     alt="{{ recipe.name }}" 
     class="img-fluid" style="max-height: 50px;">
 </span>


Solution

  • At first, for [src] case- As your image path is not static, so you are binding dynamic image path to html by [src]. The src property of the HTMLElement img is bound to the recipe.imagePath and if you change the path in the ts, it will change accordingly in html. The square braces are used to bind data to a property of an element.

    Another important use case to consider is @Input binding. Passing value from one component to another. You can pass some value from parent to child component like this-

      <app-child
        [simpleText]="someText"
        [magicText]="'Testing magic text'"
        [pubProp]="pubPropText">
      </app-child>
    

    See this example: https://stackblitz.com/edit/angular-input-example and can check this blog post too- https://blog.bitsrc.io/one-way-property-binding-mechanism-in-angular-f1b25cf00de7