Sameer
Sameer

Reputation: 3516

How to pass img binding value into another component - Angular 2+

I am getting started with Angular2 +

My first component called Page1:

import { Component } from '@angular/core';

@Component({
  selector: 'page-one',
  template: `
  <h1>Page 1</h1>
  <img src={{img}} />
  <br />
  <br />
  <a [routerLink]="['/page2']">
     Go to page 2
  </a>
  `
})
export class Page1Component {
    img = 'https://dummyimage.com/300/09f/fff.png';
}

My output looks like:

enter image description here

Now i am navigating to page2, the routing works perfectly.

My page2 component code:

import { Component } from '@angular/core';

@Component({
  selector: 'page-two',
  template: `
  <h1>Page Two!!</h1>
  <img src={{img}} />
  `
})
export class Page2Component {

}

My page 2 looks like:

enter image description here

I am not getting the page1 img into second component dynamically,

How to get that into my second component?

Upvotes: 0

Views: 1829

Answers (1)

xrobert35
xrobert35

Reputation: 2556

You have many solution for "your problem". As you can see in your exemple, component scope are "isolated" by default, they don't share variables.

So here it will depend of what you want to do :

  1. You can first pass the "img url" as an url parameter by checking the documention of the router link but, in my opinion, it's seem pretty change to do it like.

  2. You can create an Injectable() and inject it in page-two and page-one components. Injectable() are singleton instance (when they are provided by a module), they will help you to share variable and method.

    @Injectable() export class MyImgUrls{ public img1Url = 'https://dummyimage.com/300/09f/fff.png'; }

In page-one

 constructor(private myImgUrl: MyImgUrls){}

 getImgUrl(){
   return this.myImgUrl.img1Url;
 }

html :

<img [attr.src]="getImgUrl()" />

3.For you case since you only need it to manage your view, you can create a @Pipe() to share to img url between component, which will perfectly suite your needs. Pipe are usually used to "transformValue" but you can also you it to easily manage and share your case.

@Pipe({ name: 'myImgUrl', pure : true })

export class MyImgUrlPipe implements PipeTransform {

      transform() { // transform have some parameter but will don't need it in your situation
        return 'https://dummyimage.com/300/09f/fff.png'; 
      }
    }

and then in your component

<img [attr.src]=" ''| myImgUrl" />
  1. You can also create a @Directive that will work on your img tag and change the src attribute with the url.

  2. You can create a sub component used by page-one and page-two to show the img

Upvotes: 1

Related Questions