angular4.x学习笔记--指令

指令

Angular的指令概念跟AngularJS的指令差不多,最重要的区别在于Angular中的组件继承指令,算是特殊的指令。我们看下用指令的方式去写组件的简单例子:

import { Directive,Input,ElementRef } from '@angular/core';

@Directive({
    selector: 'hello'
})
export class HelloDirective { 
    @Input() name: string;

    constructor(private el: ElementRef) {}

    public ngOnInit(): void {

        this.el.nativeElement.innerText = `hello ${this.name}!`;
    }
}

// 使用组件指令
<hello name="Yecao"></hello>

// 渲染结果
<hello> hello, Yecao! </hello>

不要忘记在使用前先在模块中声明哦,我觉得这是Angular最烦人的一点。

除此之外,还有属性指令和结构指令,属性指令只改变元素的样式或者行为。要写成属性指令,需要在selector属性中用[]包裹起来。来看简单地例子:

import { Directive, ElementRef, Renderer2 } from '@angular/core';  

@Directive({   
  selector: '[highLight]'  
})  

export class HighLightDirective {    
  constructor(private el: ElementRef, private renderer2: Renderer2) { }    

  ngAfterViewInit() {   
    this.renderer2.addClass(this.el.nativeElement, 'highlight');   
  }  
}

// 使用属性指令
<p highLight> 这一段会高亮显示 </p>

结构指令就是模板中提到的*ngIf,*ngFor等指令,它修改了DOM结构。举个例子,重写*ngIf:

import { Directive, Input, ViewContainerRef, TemplateRef } from '@angular/core';   

@Directive({   
  selector: '[myIf]'  
})  

export class MyIfDirective {    

  constructor(private templateRef: TemplateRef<any>,   
      private viewContainer: ViewContainerRef) { }   

  @Input() set appMyIf(condition: boolean) {   
    if (condition) {   
      this.viewContainer.createEmbeddedView(this.templateRef);   
    } else {   
      this.viewContainer.clear();   
    }   
  }  
}  

// 使用结构指令
<p *myIf="false"> 这一段不会显示 </p> 

想要整理更多的碎片知识,扫码关注下面的公众号,让我们在哪里接着唠!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值