将类添加到Angular 4中的元素 [英] Add class to an element in Angular 4
本文介绍了将类添加到Angular 4中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用Angular 4创建图像库.其背后的逻辑是向所选图像添加级联样式表(CSS)类,该类在所选(单击)的图像上显示红色边框.这是图库的CSS样式表.
I was trying to create an image gallery with Angular 4.The logic behind this is to add a Cascading Style Sheet (CSS) class to the selected image that will show a red border on the selected (clicked) image. This is the CSS stylesheet for an image gallery.
我想在单击的图像上显示一个红色的选择方块. this-is-a-class
应该添加到所选图像中.
I want to show a red selection square on the image I have clicked. this-is-a-class
should be added to the selected image.
#container{
border:1px solid red;
height:auto;
}
ul li{
margin-right:20px;
margin-left:0;
list-style-type:none;
display:inline;
}
ul li img{
width: 200px;
height:200px;
border:1px solid grey;
}
#select{
border:2px solid violet;
}
.this-is-a-class{
border: 10px solid red !important;
}
以下是模板代码
<div id="container">
<ul>
<li><img class="this-is-a-class" id="1" src="../../assets/images/1.jpg" (click)="addClass(id=1)"/></li>
<li><img id="select" src="../../assets/images/2.png" (click)="addClass(id=2)"/></li>
<li><img id="3" src="../../assets/images/3.jpg" (click)="addClass(id=3)"/></li>
<li><img id="4" src="../../assets/images/4.png" (click)="addClass(id=4)"/></li>
<li><img id="5" src="../../assets/images/5.jpg" (click)="addClass(id=5)"/></li>
</ul>
</div>
<div>
<h1>You Clicked on: {{id}}</h1>
</div>
组件代码如下
import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
id: number;
constructor() {
console.log("Constructor working..")
}
ngOnInit() {
console.log('ngOnInit works..');
}
//function to add the class to selected image to show the border.
addClass(id) {
this.id = id;
//id = this.id? 'selectedImg' : 'null';
}
}
推荐答案
使用[ngClass]
,并根据id
有条件地应用类.
Use [ngClass]
and conditionally apply class based on the id
.
在您的HTML文件中:
<li>
<img [ngClass]="{'this-is-a-class': id === 1 }" id="1"
src="../../assets/images/1.jpg" (click)="addClass(id=1)"/>
</li>
<li>
<img [ngClass]="{'this-is-a-class': id === 2 }" id="2"
src="../../assets/images/2.png" (click)="addClass(id=2)"/>
</li>
在您的TypeScript文件中:
addClass(id: any) {
this.id = id;
}
这篇关于将类添加到Angular 4中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文