在我的html中,我想將屬性綁定應用到每個元素。如何阻止屬性綁定到Angular中的每個元素* ngFor
我有一個點擊和懸停事件,我想要做的只要用戶 盤旋或單擊一個單獨的元素。但是現在,點擊發生在
*ngFor
內的每個元素都會發生點擊或 。我希望它只在 發生在他們正在選擇/懸停的元素上。我需要什麼 更改?我看到了另一個計算器的答案,他們只是應用的名稱 中的for循環:在布爾值/變量,他們設置的前面(前
*ngFor="let article of articles"
他們 使用article
)。 像我的布爾值是favorite
所以他們做article.favorite
內 該元素,它顯然工作,但該方法不適用於 我。代碼:
<div class="row">
<!--/span-->
<div class="col-6 col-sm-6 col-lg-4"
*ngFor="let article of articles">
<h2>{{article.title}}</h2>
<h4>By: {{article.author}}</h4>
<p>{{article.body}}</p>
<div class="col-lg-4">
<button type="button" class="btn btn-default" (click)="addFavorite()"
(mouseenter)="hoverFavorite()"
(mouseleave)="removeHoverFavorite()">
<span
class="glyphicon"
[class.glyphicon-heart]="favorite"
[class.glyphicon-heart-empty]="!favorite"
aria-hidden="true"></span> Favorite
</button>
</div>
<div class="col-lg-4">
<button type="button" class="btn btn-default">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Comment
</button>
</div>
<div class="col-lg-4">
<button type="button" class="btn btn-info pull-left" [routerLink]="['/articles', article.articleId]">Read More »
</button>
</div>
</div>
</div>
<!--/row-->
添加組件
import { Component, OnInit } from '@angular/core';
import {ArticlesService} from "./articles.service";
import {Article} from "./article.model";
import {Router} from "@angular/router";
@Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {
articles: Article[];
// if favorite = false then full heart is not shown. if true then heart shown
favorite: boolean = false;
// clicked will be used to determine if we should keep hovering effect on
clicked: boolean = false;
constructor(private router: Router, private articleService: ArticlesService) { }
ngOnInit() {
this.articleService.getArticles()
.subscribe(
(articles: Article[]) => {
this.articles = articles;
}
);
}
addFavorite(){
// toggle full and empty heart
this.clicked = !this.clicked;
if (this.clicked === true){
// if clicked then add to database and show full heart
this.favorite = true;
} else { // if false then remove from database and show empty heart
this.favorite = false;
}
}
hoverFavorite(){
// if clicked is false then show hover effect, else dont
if (this.clicked === false){
this.favorite = true;
}
}
removeHoverFavorite(){
// if clicked is false then show hover effect, else dont
if (this.clicked === false){
this.favorite = this.favorite = false;
}
}
}
不適用於我..在鼠標上輸入並保留它說它必須是一個左值 – XXIV
您需要在組件中創建一個字段'hoverFavorite:number'。 –
如果我這樣做,那麼這消除了我要求鼠標輸入(hoverFavorite)和鼠標離開(removeHoverFavorite)的功能。另外,爲什麼在撥打鼠標離開時我會在索引上下降一位?難道這仍然不會保持當前(i)的懸停效果,但是在它之前取消懸停效果(這不會有用,因爲懸停效果不應該在索引之前在索引上) ? – XXIV