簡體   English   中英

Angular2如何更新另一個組件中的圖像

[英]Angular2 how to update image in another component

我有兩個組件,一個是頂部欄,另一個是個人資料管理頁面。

問題在於更新個人資料圖片時,它也應該從頂部欄標題中進行更改。 它可以,但是頁面會重新加載。 我希望它能即時顯示。

為此,如果我在頂部欄組件中單擊一個函數並更改顯示圖像的變量,則可以執行此操作。 但是我無法弄清楚該怎么做,我的意思是,如果在my-profile組件中更新了圖像,那么我該如何調用top-bar組件的函數並更改變量的值。

我試過的是:

top-bar.component.ts:

@Component({


selector: 'top-bar',
  templateUrl: './top-bar.component.html',
})
export class TopBarComponent {
     @Output() myEvent = new EventEmitter();
       test()
    {
    console.log("in test");
    }
   }

my-profile.component.html:

<top-bar #modal></top-bar>
    <top-bar (myEvent)="modal.test()"></top-bar>

我希望在我的個人資料頁面加載中,我應該得到console.log(“ in tets”);。 如果錯誤,請糾正我,我該如何解決。 謝謝

我已經在我的個人資料組件中導入了頂欄組件

我假設您在頂部欄組件中有一個圖像元素。 您將需要為該組件創建一個輸入,將其綁定到圖像。

因此,您將在課堂上的某個位置執行此操作。

export class TopBarComponent {
    @Input() imageSrc: string;
}

您將在模板中使用的模板

<img [src]="imageSrc"></img>

這是工作正常的PLUNKER組件。.這可能會對您有幫助,在這里頭圖像通過配置文件組件進行更改。

標頭組件:

@Component({
             selector: 'app-header',
             template: `<header>
                       <img [src]="imgSrc"> 
                       <app-profile (reloadParent)="setImage($event)" 
                       [imgUrl]="imgSrc"></app-profile>
                       </header>`
      })
export class HeaderComponent implements OnInit {
   imgSrc;
   constructor() { }
   ngOnInit() {
   this.setImage({src: "http://files.softicons.com/download/system-
                 icons/oxygen-icons-by-
   oxygen/png/128x128/actions/format_font_size_less.png"});
 }
  setImage($event){
  this.imgSrc = $event.src;
  }
}

配置文件組件

@Component({
           selector: 'app-profile',
           template: `<div id="">
           <img [src]="imgUrl">
           <button (click)="changeImage()">Change Image</button>
           </div>`
   })
  export class SearchComponent implements OnInit {
  @Input() imgUrl: string;
  @Output() reloadParent: EventEmitter<any> = new EventEmitter<any>();
  constructor() { }
  ngOnInit() {     }
  changeImage(){
       var img = "https://encrypted-tbn0.gstatic.com/images?
        q=tbn:ANd9GcQWVbaiDV_SRbWJJVfyn7wOinekRzs9xiCHdZK5RU86bkICXcaz";
        this.reloadParent.emit({src: img });
     }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM