可以使用Angular中提供的Directive来实现,具体实现方法如下:
HTML代码部分:
TypeScript代码部分:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appChangeText]'
})
export class ChangeTextDirective {
@Input() fruitColor: string;
constructor(private el: ElementRef) {}
@HostListener('click') onClick() {
this.el.nativeElement.style.color = this.fruitColor;
}
}
其中,appChangeText是Directive的selector,ChangeTextDirective是Directive的类名。
在HTML中,我们在
在TypeScript中,则定义了一个ChangeTextDirective类,该类中实现了@Input来接收用户设置的水果颜色,@HostListener则监听点击事件,通过this.el.nativeElement.style.color设置水果颜色。
完整代码实现示例:
HTML代码
{{selectedFruit}} is my favourite fruit. Click below to change the color.
TypeScript代码
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appChangeText]'
})
export class ChangeTextDirective {
@Input() fruitColor: string;
constructor(private el: ElementRef) {}
@HostListener('click') onClick() {
this.el.nativeElement.style.color = this.fruitColor;
}
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
fruits = ['Apple', 'Banana