我是angular2的初学者,我在jquery和html中有以下代码。 我必须在angular2中实现它。做这个的最好方式是什么。 我的一位朋友建议我做元素参考。但我不知道 请用示例和解释建议我最好的方法。
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$('.btn').click(function(){
$(this).parent().css("background-color","yellow");
})
})
</script>
</head>
<body>
<div style="background-color:black; width:200px; height:50px; margin:10px;">
<input class="btn" type="button" value="change color" style="" />
</div>
<div style="background-color:cyan; width:200px; height:50px; margin:10px;">
<input class="btn" type="button" value="change color" style="" />
</div>
<div style="background-color:green; width:200px; height:50px; margin:10px;">
<input class="btn" type="button" value="change color" style="" />
</div>
</body>
</html>
答案 0 :(得分:1)
有几种方法可以在angular2中存档它,我在这里使用构造函数中的intilization或 For i = 1 To sFolders.Count
If sFolders.Item(i).Name = dFolders.Item(i).Name Then
Call CopyMail(sFolders.Item(i), dFolders.Item(i))
ElseIf sFolders.Item(i).Name IsNot dFolders.Item(i).Name Then
dFolderN = dFolderR.Folders.Add(sFolders.Item(i).Name)
End If
Next
这样的角度钩子
ngOnInit
在html中
ngOnInit() {
$('.btn').click(function(){
$(this).parent().css("background-color","yellow");
})
}
PS:基本上你可以在构造函数中添加你想要在文档加载中使用的代码,就像在<div style="background-color:black; width:200px; height:50px; margin:10px;">
<input id='abc' class="btn" type="button" value="change color" style="" />
</div>
<div style="background-color:cyan; width:200px; height:50px; margin:10px;">
<input id='abc' class="btn" type="button" value="change color" style="" />
</div>
<div style="background-color:green; width:200px; height:50px; margin:10px;">
<input id='abc' class="btn" type="button" value="change color" style="" />
</div>
答案 1 :(得分:0)
您的朋友建议是解决问题的好方法:
要使用ElementRef,您应该创建一个(属性)指令(https://angular.io/guide/attribute-directives)
您需要ElementRef来获取实施指令的DOM中的当前元素。
我建议您阅读有关这些内容并阅读Angular页面上的教程
以下是一个例子:
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
declare const $: any; // Reverse for jQuery. Don't forget to include jQuery in your project!
@Directive({
selector: '[appButton]'
})
export class ButtonDirective implements AfterViewInit {
constructor(private el: ElementRef) { }
ngAfterViewInit(): void {
$(this.el.nativeElement).click(function(){
$(this).parent().css({
'background-color': 'yellow'
});
});
}
}
要最终使用此指令,请执行以下操作:
<div style="background-color:black; width:200px; height:50px; margin:10px;">
<input appButton class="btn" type="button" value="change color" style="" />
</div>
<div style="background-color:cyan; width:200px; height:50px; margin:10px;">
<input appButton class="btn" type="button" value="change color" style="" />
</div>
<div style="background-color:green; width:200px; height:50px; margin:10px;">
<input appButton class="btn" type="button" value="change color" style="" />
</div>