首页 > 其他 > 详细

angular学习3-指令

时间:2021-05-23 09:17:44      阅读:13      评论:0      收藏:0      [点我收藏+]

7. angular指令

7.1 内置指令

angular提供两种内置指令:结构指令和属性指令

内置指令仅仅使用了公共 API。也就是说,它们没有用到任何其它指令无权访问的私有 API。

7.1.1内置属性指令

通常应用在元素或者组件上,监听他们的行为、attribute和property,就像元素属性一样。

ngClass: 同时添加或者删除一个或者多个css类

ngStyle:可以通过style属性绑定的方式更改单个样式;也可以通过ngStyle添加对象的方式设置多个样式

ngModel: 双向数据绑定

  • 使用 ngModel 指令,必须先导入 FormsModule 并将其添加到 NgModule 的 imports 列表中

  • 因此 NgModel 指令仅适用于通过 ControlValueAccessor 适配过这种协议的元素。Angular 已经为所有基本的 HTML 表单元素提供了值访问器

7.1.2 内置结构指令

结构指令通过添加、移除它们的宿主元素来塑造和控制dom结构。

内置结构指令前面要加上*。

当指令没有合适的宿主,可以用<ng-container>对元素进行分类

ngIf:添加或者删除元素。

  • ngIf删除元素会从dom结构中删除该元素以及这个元素的子结构

  • 应用:防范空指针错误

    <div *ngIf="currentCustomer">Hello, {{currentCustomer.name}}</div>

 

ngFor:重复指令。用来显示条目列表的方法。

<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>

ngSwitch: 官网

 

7.2自己创建一个属性指令

7.2.1 创建一个简单的自定义属性指令

创建指令类文件

ng generate directive highlight

highlight.directive.ts的内容更改如下

import { Directive, ElementRef, HostListener } from ‘@angular/core‘;
// @HostListener装饰器让你订阅属性指令所在宿主dom元素的事件。
// 你可以在指令的构造函数中使用 ElementRef 来注入宿主 DOM 元素的引用,也就是你放置 appHighlight 的那个元素。
?
@Directive({
 selector: ‘[appHighlight]‘
})
export class HighlightDirective {
   
@HostListener(‘mouseenter‘) onmouseenter() {
  console.log(‘enter‘)
}
?
 @HostListener(‘mouseleave‘) onmouseleave() {
   console.log(‘leave‘)
}
 // 构造函数接收一个参数:el,通过el可以直接访问宿主元素
 // 当在宿主元素上面发现appHighlight属性,就会创建一个HighlightDirective实例
 constructor(el: ElementRef) {
   console.log(el)
   el.nativeElement.style.backgroundColor = ‘yellow‘;
}
?
}

使用:

<p appHighlight>我使用了自定义指令</p>

7.2.2 处理器委托辅助方法来操作dom元素:

import { Directive, ElementRef, HostListener } from ‘@angular/core‘;
?
@Directive({
 selector: ‘[appHighlight]‘
})
export class HighlightDirective {
 constructor(private el: ElementRef) { }
?
 @HostListener(‘mouseenter‘) onMouseEnter() {
   this.highlight(‘yellow‘);
}
?
 @HostListener(‘mouseleave‘) onMouseLeave() {
   this.highlight(null);
}
?
 private highlight(color: string) {
   this.el.nativeElement.style.backgroundColor = color;
}
}

7.2.3通过@input向自定义指令传值

  1. 绑定@input属性

    import { Directive, ElementRef, HostListener, Input } from ‘@angular/core‘;
    ?
    @Directive({
     selector: ‘[appHighLightWithInput]‘
    })
    export class HighLightWithInputDirective {
     ...
     // 在指令文件中可以直接通过this.highLightColor访问传进来的值
     @Input() highLightColor:string
     
     constructor(el: ElementRef) {
       ...
    }
    ?
    }
    ?

     

  2. 绑定@input别名

 

angular学习3-指令

原文:https://www.cnblogs.com/lovlyGir/p/14800151.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!