《Angular学习四》属性型指令
属性型指令
创建属性指令 ng generate directive highlight
<input type="text" id="hero-name" [(ngModel)]="hero.name">
export class AppComponent {
title = 'ng-wyy';
color='';
}
<div>
<input type="radio" name="colors" (click)="color='lightgreen'">Green
<input type="radio" name="colors" (click)="color='yellow'">Yellow
<input type="radio" name="colors" (click)="color='cyan'">Cyan
</div>
<p [appHighlight]="color">Highlight me!</p>
export class HighlightDirective {
constructor(private el:ElementRef) {
// 构造函数
}
@Input() appHighlight='';
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');//监听鼠标进入
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight('');//监听鼠标移出
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = this.appHighlight;//设置背景颜色
}
}
说明:
(click)="color='yellow'鼠标点击单选按钮,color的值为yellow
<p [appHighlight]="color">Highlight me!</p> [appHighlight] 的值为color的值。
this.el.nativeElement.style.backgroundColor = this.appHighlight;这只背景色为Color的值。
鼠标点击->Color = yellow-> apphighlight = Color 。
[appHighlight]使用,需要定义@Input() appHighlight='';
案例
<p appHighlight>鼠标移动上去变色</p>//前台代码
ng generate directive highlight//生成属性指令
highlight.directive.ts//生成的文件名
import { Directive, ElementRef, HostListener } from '@angular/core';
//属性型指令 ng generate directive highlight
@Directive({
selector: '[appHighlight]'//指定名称
})
export class HighlightDirective {
constructor(private el:ElementRef) {
// 构造函数
}
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');//监听鼠标进入
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight('');//监听鼠标移出
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;//设置背景颜色
}
}
通过 NgNonBindable
停用 Angular 处理过程
<p>Use ngNonBindable to stop evaluation.{{ 1 + 1 }}</p>
<p ngNonBindable>This should not evaluate: {{ 1 + 1 }}</p>
<h3>ngNonBindable with a directive</h3>
<div ngNonBindable [appHighlight]="'yellow'">This should not evaluate: {{ 1 +1 }}, but will highlight yellow.
</div>
输出
Use ngNonBindable to stop evaluation.2
This should not evaluate: {{ 1 + 1 }}
ngNonBindable with a directive
This should not evaluate: {{ 1 +1 }}, but will highlight yellow.
近期评论