在自定义指令中实现 onclick() angular 4
implement onclick() in custom directive angular 4
我有一个简单的按钮和一个指令,我想访问按钮的样式,在指令中添加带有 onclick() 函数的 MarginLeft 它不起作用,但是从构造函数中设置 css 可以工作我怎么能将其与点击一起使用?请帮助:
指令:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[Bluecolored]'
})
export class BluecoloredDirective {
constructor(private element:ElementRef) {
console.log(element);
element.nativeElement.style.color="blue";
}
clicked(){
this.element.nativeElement.style.marginLeft=20;
console.log("marzi"+this.element.nativeElement.style.marginLeft);
}
}
这是模板:
<p Bluecolored>
new-fom works!
</p>
<h1 Bluecolored>Blue Colored</h1>
<button (click)="clicked()" Bluecolored>Click</button>
您可以在指令中使用 HostListener:
@HostListener('click') onClick(){
this.element.nativeElement.style.marginLeft=20;
console.log("marzi"+this.element.nativeElement.style.marginLeft);
}
这样你也可以通过按钮(click)="clicked()"
遥控
我将其命名为 onClick,但您也可以将其命名为 clicked
我有一个简单的按钮和一个指令,我想访问按钮的样式,在指令中添加带有 onclick() 函数的 MarginLeft 它不起作用,但是从构造函数中设置 css 可以工作我怎么能将其与点击一起使用?请帮助:
指令:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[Bluecolored]'
})
export class BluecoloredDirective {
constructor(private element:ElementRef) {
console.log(element);
element.nativeElement.style.color="blue";
}
clicked(){
this.element.nativeElement.style.marginLeft=20;
console.log("marzi"+this.element.nativeElement.style.marginLeft);
}
}
这是模板:
<p Bluecolored>
new-fom works!
</p>
<h1 Bluecolored>Blue Colored</h1>
<button (click)="clicked()" Bluecolored>Click</button>
您可以在指令中使用 HostListener:
@HostListener('click') onClick(){
this.element.nativeElement.style.marginLeft=20;
console.log("marzi"+this.element.nativeElement.style.marginLeft);
}
这样你也可以通过按钮(click)="clicked()"
遥控
我将其命名为 onClick,但您也可以将其命名为 clicked