Angular 找不到名称“srcelelement”
我有两个按钮用于呕吐,点击时我会调用一种方法,比较上下点击的次数,并根据结果改变背景颜色 但是编辑器显示找不到名称“srcElement” 也许我的方法不完整Angular 找不到名称“srcelelement”,angular,typescript,Angular,Typescript,我有两个按钮用于呕吐,点击时我会调用一种方法,比较上下点击的次数,并根据结果改变背景颜色 但是编辑器显示找不到名称“srcElement” 也许我的方法不完整 yes= 0; no = 0; constructor() { } ngOnInit() { } onYes(index: number){ this.yes ++; this.onWhich(); } onNo(index: number){ this.no ++; this.onWhich(); } onWhi
yes= 0;
no = 0;
constructor() { }
ngOnInit() {
}
onYes(index: number){
this.yes ++;
this.onWhich();
}
onNo(index: number){
this.no ++;
this.onWhich();
}
onWhich(){
if(this.yes > this.no){
srcElement.parentElement.style.backgroundColor = 'blue';
}else if(this.yes < this.no){
srcElement.parentElement.style.backgroundColor = 'red';
}else{
srcElement.parentElement.style.backgroundColor = 'white';
}
}
这是模板
{{post.title}} 爱死它了! 不要爱它! 在引用模板/component.html上的DOM元素时,可以使用
首先,我们使用字符声明两个按钮的模板引用变量<ul class="list-group">
<li class="list-group-item" *ngFor="let post of posts; let i = index">
<p style="font-size:35px;"> {{ post.title }}
<button class="btn btn-success" (click)="onYes(i)" #buttonYes>Love it!</button>
<button class="btn btn-danger" (click) ="onNo(i)" #buttonNo>Don't love it!</button> <br>
</li>
</ul>
我创造了一个新的世界
或者,更好的解决方案是使用ngClass,根据每个帖子的“是”和“否”投票数,有条件地应用类.list group item success和.list group item danger
.我将采用与wentjun相同的方法添加属性yes和no,但我不会从TS文件中操作DOM,相反,我们可以使用ngClass和应用样式类。比如说像这样的课程:
.blue-bg {
background-color: blue;
}
.red-bg {
background-color: red;
}
.white-bg {
background-color: white;
}
如果您有一个现有的帖子数组,则可以使用以下内容添加新属性:
this.posts=this.posts.mappost=>{return{…post,yes:0,no:0};
然后为按钮(如wentjun)添加单击处理程序并传递索引:
爱死它了!
不要爱它!
以及相应的功能:
奥涅西:号码{
this.posts[i].yes++;
}
安诺伊:号码{
this.posts[i].no++;
}
然后在模板中标记ngClass中的条件:
[ngClass]=[post.yes>post.no.“蓝色背景”:,
post.yes<ul class="list-group">
<li class="list-group-item" *ngFor="let post of posts; let i = index">
<p [ngClass]="{
'list-group-item-success': post.yes > post.no,
'list-group-item-danger': post.yes < post.no}" style="font-size:35px;"> {{ post.title }}
<button class="btn btn-success" (click)="onYes(i)" #buttonYes>Love it!</button>
<button class="btn btn-danger" (click) ="onNo(i)" #buttonNo>Don't love it!</button>
</p>
</li>
</ul>
.list-group-item-success {
background-color: blue;
}
.list-group-item-danger {
background-color: red;
}
.blue-bg {
background-color: blue;
}
.red-bg {
background-color: red;
}
.white-bg {
background-color: white;
}