如何使用 angular 2 且仅 javascript 访问指令中的当前元素
How get acces to the current element in a directive with angular 2 and only javascript
我在 angular 2 和 Javascript。
在指令中,我需要访问当前元素才能操作 DOM。
请注意,我不能使用主题标签 (#element
) 的技巧,因为我会有很多这样的元素。每一个都会有我的指示。
Html
<p [focus]="p1.focus"></p>
<p [focus]="p2.focus"></p>
<!-- ... -->
Javascript
(function (app) {
app.Focus =
ng.core.Directive({
selector: "[focus]",
inputs: ['focus'],
}).Class({
constructor: function() {
// how get access to the current element here
}
})
})(window.app || (window.app = {}));
你知道我该怎么做吗?
不幸的是,javascript
的官方文档不是很清楚
我不知道如何在 javascript 中编写此代码,但如果此 typescript 代码可以帮助您。
import { Component, ElementRef,Renderer } from '@angular/core';
@Directive({
selector: "[focus]",
inputs: ['focus'],
host: {
'(click)':'click()',
},
})
export class myDirective{
constructor(private el:ElementRef) {
console.log(el)//<-----------current element
}
click(){
console.log(this.el) //<------------current element
}
}
我的错误,我忘了在javascript中注入。好的答案是:
constructor: [ ng.core.ElementRef, function(elementRef) {
// elementRef.nativeElement
}]
我使用此 javascript 更改活动主题的 css 文件。也许你可以调整一下:
var KetoApp = {
changeTheme: function(event, element) {
var theme = $(element).data("theme"),
themeLink = $('link[href$="theme.css"]'),
newThemeURL = 'node_modules/primeng/resources/themes/' + theme + '/theme.css';
themeLink.attr('href', newThemeURL);
event.preventDefault();
}
};
我在 angular 2 和 Javascript。
在指令中,我需要访问当前元素才能操作 DOM。
请注意,我不能使用主题标签 (#element
) 的技巧,因为我会有很多这样的元素。每一个都会有我的指示。
Html
<p [focus]="p1.focus"></p>
<p [focus]="p2.focus"></p>
<!-- ... -->
Javascript
(function (app) {
app.Focus =
ng.core.Directive({
selector: "[focus]",
inputs: ['focus'],
}).Class({
constructor: function() {
// how get access to the current element here
}
})
})(window.app || (window.app = {}));
你知道我该怎么做吗?
不幸的是,javascript
的官方文档不是很清楚我不知道如何在 javascript 中编写此代码,但如果此 typescript 代码可以帮助您。
import { Component, ElementRef,Renderer } from '@angular/core';
@Directive({
selector: "[focus]",
inputs: ['focus'],
host: {
'(click)':'click()',
},
})
export class myDirective{
constructor(private el:ElementRef) {
console.log(el)//<-----------current element
}
click(){
console.log(this.el) //<------------current element
}
}
我的错误,我忘了在javascript中注入。好的答案是:
constructor: [ ng.core.ElementRef, function(elementRef) {
// elementRef.nativeElement
}]
我使用此 javascript 更改活动主题的 css 文件。也许你可以调整一下:
var KetoApp = {
changeTheme: function(event, element) {
var theme = $(element).data("theme"),
themeLink = $('link[href$="theme.css"]'),
newThemeURL = 'node_modules/primeng/resources/themes/' + theme + '/theme.css';
themeLink.attr('href', newThemeURL);
event.preventDefault();
}
};