0
我是Angular 2的新手,這是官方網站的代碼。我理解所有的類,導入,列表,HTML標籤。但我不明白選擇(英雄)metod。 * ngFor直播列表ID和名稱。如果我們選擇列表,則會顯示詳細信息。該方法如何工作?它抓住了數據,但以什麼方式對我不明確。Angular 2 Master/Detail nead的解釋
import { Component } from '@angular/core';
export class Hero {
id: number;
name: string;
}
const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
@Component({
selector: 'my-app',
template:
'
<h1>{{title}}</h1>
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
<div *ngIf="selectedHero">
<h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="selectedHero.name" placeholder="name"/>
</div>
</div>
`,
styles: [`
.selected {
background-color: #CFD8DC !important;
color: white;
}
.heroes {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.heroes li.selected:hover {
background-color: #BBD8DC !important;
color: white;
}
.heroes li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.heroes .text {
position: relative;
top: -3px;
}
.heroes .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607D8B;
line-height: 1em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
`]
})
export class AppComponent {
title = 'Tour of Heroes';
heroes = HEROES;
selectedHero: Hero;
onSelect(her: Hero): void {
this.selectedHero = her;
}
}
感謝您的解釋。我有更多的問題。在該方法中綁定項目並使用selectedHero值顯示在其他HTML上,如{{selectedHero.name}}?英雄在(click)=「onSelect(英雄)是來自* NgFor的值?什麼是她在onSelect(她:英雄):void { this.selectedHero =她; } 謝謝 –
@StoiljkovićMiloš」她「是onSelect方法參數的名稱,onSelect(her:Hero)定義表示'onSelect'方法只有一個參數(名爲'her')'Hero'類型。不知道我是否正確理解了問題的其餘部分,但Angular2將'AppComponent'中定義的屬性綁定到生成的html,所以如果你在你的html模板中使用'{{selectedHero.id}}',然後改變代碼中'selectedHero'屬性的值,HTML視圖應該反應並顯示新值。 – kmaczuga