打字稿新手,我必须隐藏用户点击的div。
以下是我的代码:
<div class="tiles" *ngFor="let episode of episodes; let i = index" (click)="showDetails(i)" style="width:100px;height:100px;border:2px solid black">
{{episode.title}}
</div>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
showDiv:boolean = false;
episodes = [
{ title: 'Winter Is Coming', director: 'Tim Van Patten' },
{ title: 'The Kingsroad', director: 'Tim Van Patten' },
{ title: 'Lord Snow', director: 'Brian Kirk' },
{ title: 'Cripples, Bastards, and Broken Things', director: 'Brian Kirk' },
{ title: 'The Wolf and the Lion', director: 'Brian Kirk' },
{ title: 'A Golden Crown', director: 'Daniel Minahan' },
{ title: 'You Win or You Die', director: 'Daniel Minahan' },
{ title: 'The Pointy End', director: 'Daniel Minahan' }
];
showDetails(i):void{
this.showDiv = !this.showDiv;
}
}
上面的代码将填充总共8个div。因此,一旦点击第一个div,它应该隐藏,其他div应该接管它的位置,类似当点击第二个div时它应该隐藏(第一个应该显示可见),其他div应该接管它的位置。
答案 0 :(得分:1)
这个想法是有一个变量“indexHidden”,当indexHidden == i时,你隐藏了“div”。但你不能在同一个“div”上做到这一点。
因此,我们使用ng-container https://angular.io/guide/structural-directives#ng-container-to-the-rescue来执行* ngFor
<ng-container *ngFor="let episode of episodes; let i = index">
<div *ngIf="i!=indexHidden" (click)="indexHidden=i" class="tiles"
style="width:100px;height:100px;border:2px solid black">
{{episode.title}}
</div>
</ng-container>
//in your component.ts
indexHidden:number=-1 //At first equal=-1, so all episodes are showed
答案 1 :(得分:1)
试试这个
<div *ngFor="let episode of episodes; let i = index">
<div class="tiles" *ngIf='i !== hide' (click)="hide = i" style="width:100px;height:100px;border:2px solid black">
{{episode.title}} {{i}}
</div>
</div>
答案 2 :(得分:1)
这是一种方法(组件中不需要任何变量。模板中的所有逻辑:
<div class="tiles" *ngFor="let episode of episodes; let i = index" (click)="showDetails(i)" style="width:100px;height:100px;border:2px solid black">
<span #itm [hidden]="itm[i]" (click)="itm[i] = true ">{{episode.title}}</span>
</div>
P.S。您可以将[hidden]
替换为*ngIf
,以便在大多数情况下性能会提高
答案 3 :(得分:0)
在每集的对象上添加属性showDiv。
示例:
episodes = [{showDiv: true, title: 'xxxxxx', ....}]
答案 4 :(得分:-1)
在这种情况下,我不会使用ngFor,我们几乎实现了carouse, 并且您不再需要使用ngFor或ngIf并且继续循环对象(剧集)
app.component.html
MVC
app.component.ts
<div class="tiles" (click)="showNext()" style="width:100px;height:100px;border:2px solid black">
{{currentEpisode.title}}
</div>