3
我通過創建簡單的項目來學習Angular 2,這裏是應用程序的Plunker。ng2 - 傳遞來自兄弟組件指令的信息
它有兩個定製的組件,
- 視頻list.ts
- 視頻player.ts
上述兩個部件都使用他們的指令顯示在app.ts
compontent 。
視頻播放器組件應該將任何點擊的歌曲顯示爲{{ nowPlaying }}
變量,因爲歌曲列表位於視頻列表組件中,我無法理解如何傳遞點擊的歌曲項並在視頻列表中顯示其標題,播放器組件。
雖然,視頻播放器組件有一個@Input
裝飾爲nowPlaying
對象變量,但我不知道如何通過從視頻列表組件的應用程序組件達到選定的對象。
我還在應用程序組件中添加了一個nowPlayingDefault
變量,以默認將它傳遞給視頻播放器組件。
下面是代碼:(https://plnkr.co/edit/Tt0zLudPqhrBfG0iffj1)
app.ts
// root app component
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { VideoList } from './video-list';
import { VideoPlayer } from './video-player';
@Component({
selector: 'my-app',
template: `
<div class='block'>
<h2>Hello {{name}}</h2>
<video-player [nowPlaying]='nowPlayingDefault'></video-player>
<hr>
<video-lists></video-lists>
</div>
`,
})
export class App {
nowPlayingDefault:string = 'Please select a song.';
constructor() {
this.name = 'Angular2'
}
}
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [
App,
VideoList,
VideoPlayer
],
bootstrap: [ App ]
})
export class AppModule {}
視頻list.ts
import { Component } from '@angular/core';
@Component({
selector: 'video-lists',
template: `
<div id='video-lists' class='block'>
<div style='text-align: center;'>
From Video List Component
</div>
<a href='' style='display: block'
*ngFor='let item of items'
(click)='selectSong(item, $event)'>
{{ item.title }}
</a>
</div>
`
})
export class VideoList {
test: string = 'sos';
items = [
{
'title' : 'yo test',
'url' : '823ery783dh.mp3'
},
{
'title' : 'yall rappin',
'url' : '25wd13edc1.mp3'
}
];
selectSong(item, event)
{
event.preventDefault();
console.log(item);
}
}
視頻player.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'video-player',
template: `
<div id='video-player' class='block'>
<div style='text-align: center'>~ Video Player Block ~ </div>
<div style='color: blue;'>{{ nowPlaying }}</div>
</div>
`
})
export class VideoPlayer {
@Input() nowPlaying: string = 'Please select a song.';
}
如何將點擊歌曲標題從視頻列表組件中顯示到視頻播放器組件的nowPlaying
變量中?
這是給一個'錯誤:( SystemJS)錯誤:模板解析錯誤:(...)' 你能解釋這一行嗎?(selectedChange)=「nowPlaying =」event「 – rakibtg
三是錯誤修正。 is.selectedChange.emit(item)'被調用,然後評估'(selectedChange)=「xxx」中的表達式'xxx',並且'$ event'包含傳遞的'item'值。 https://angular.io/docs/ts/latest/guide/包含所有信息。 –