【发布时间】:2017-08-25 12:00:47
【问题描述】:
我正在学习 AngularJS,我需要一些帮助。
我有一个这样的模板
<div *ngFor="let beat of data" (invoke)="myFunction(beat.id)" class="item">
<div class="item-column-1 inline">
<div class="item-column-1-container">
<img class="item-img1" src="/CMP.jpg">
<p>{{beat.uploader}}</p>
</div>
</div>
<div class="item-column-2 inline">
<span class="item-title">{{beat.title}}</span>
<p class="item-score">245 </p>
<span>#TRAPCHILL</span>
<p>#TYGA #DRAKE #YOUNG THUG #MIGOS</p>
<P>Posted: 2 days ago</P>
<!-- <input (click)="rate(beat.id,1)" alt="beat.id" type="radio" id="star1" name="rating" value="1" /><label class = "full" for="star1" title="{{beat.id}}">1</label>
<input (click)="rate(beat.id,2)" alt="beat.id" type="radio" id="star2" name="rating" value="2" /><label class = "full" for="star2" title="{{beat.id}}">2</label>
<input (click)="rate(beat.id,3)" alt="beat.id" type="radio" id="star3" name="rating" value="3" /><label class = "full" for="star3" title="{{beat.id}}">3</label> -->
<div (click)="rate(beat.id,1)" class="flamme"></div>
<div (click)="rate(beat.id,2)" class="flamme"></div>
<div (click)="rate(beat.id,3)" class="flamme"></div>
<span></span>
</div>
<button (click)="play(beat.path)" type="button" name="button">play</button>
<button (click)="sendMsg()">Send</button>
<div class="item-column-3 inline">
<img class="album-cover" src="{{beat.path_img}}" alt="">
</div>
</div>
现在,对于我的 ngFor 中的每个数据,我想调用一个函数(在 发生 myFunction(beat.id)),这个函数会返回一个数字。
我想检索返回函数的编号,以显示在 我的 ngFor 的每个数据...
我尝试创建一个带有输出事件的指令“invoke”,并且 然后在我的 ngAfterContentInit() 中,我发出了我的输出,但什么也没有 发生了,加载我的数据时没有触发。
@Directive({ selector: '[invoke]'})
export class MainComponent implements OnInit {
retrievedObject : any;
src : string;
data : any;
current:any;
rating : any;
countRate : any;
subscription: Subscription;
duration:any;
@Output() invoke:EventEmitter<boolean> = new EventEmitter();
---
ngAfterContentInit() {
this.invoke.emit(null);
}
myFunction(beat_id){
alert('trigged');
}
所以如果有人有解决方案..谢谢!
【问题讨论】:
-
这是一个非常糟糕的主意。你能详细说明你需要这个吗?每次 Angular 运行变化检测时,都会调用这个函数。这会显着降低页面的性能。
-
"我想检索返回函数的编号,以便在我的 ngFor 的每个数据中显示它..." 为此,要么创建一个管道,要么预先计算每个项目的值代码中的数组并将其添加到数组或创建一个新数组,其中值与它们关联的原始数组的索引匹配。然后,您可以使用
*ngFor的...;let i=index"来访问第二个数组的值,该数组的索引与*ngFor正在迭代的数组的索引相同。 -
@Brayan 你不是在学习 AngularJS(又名 Angular 1),而是在学习 Angular(又名 Angular 2/4)。我知道这很令人困惑。
-
Brayan233,你为什么不遍历构造函数中的项目并在那里进行计算。您可以在每次迭代时将计算值附加到对象。然后它将在对象本身的 ngFor 中可用。
-
我的需要是:我有一些数据用 NgFor 显示,对于每个数据,我不想用参数(ngFor 的某个值)调用一个函数,然后显示函数的返回值对于每个我的数据。 @GünterZöchbauer
标签: javascript angular rxjs observable