For example you have a component, which take a trasclude input element:

            <au-fa-input id="password-field" icon="lock" >
<input placeholder="Password" class="test-class">
</au-fa-input>

There is many ways to get ElementRef of the input, for example using Reference:

            <au-fa-input id="password-field" icon="lock" >
<input #input placeholder="Password" class="test-class">
</au-fa-input>

We add a #input ref, so that inside component, we can using @ContentChild and AfterContentInit lifecycle:

export class AuFaInputComponent implements AfterContentInit{

    @Input()
icon: string; @ContentChild('input')
input: HTMLInputElement; ngAfterContentInit () {
console.log("input", this.input);
}

This approach works fine, but it requires us to put a element ref onto the input field.

One way to avoid putting a reference is creating a directive ref, and we can add common functionalitiy to it, such as focus and blur events:

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

@Directive({
selector: 'au-fa-input input'
})
export class InputRefDirective { focus = false; @HostListener('focus')
isFocus() {
console.log("now focus");
this.focus = true;
} @HostListener('blur')
isBlur() {
console.log("now blur");
this.focus = false;
}
}

And we our component, we need to change @ContentChild:

    @ContentChild(InputRefDirective)
input: InputRefDirective;

So for now, in html, we don't need #input any more:

            <au-fa-input id="password-field" icon="lock" >
<input placeholder="Password" class="test-class">
</au-fa-input>

Now, let's say if we want to add some styling base on whether input field is focused or not.

First, some css class:

// component

:host(.input-focus) {
border-color: #4D90FE;
-webkit-box-shadow: 0 0 5px #4D90FE;
box-shadow: 0 0 5px #4D90FE;
}

Use the function form to apply host styles conditionally by including another selector inside parentheses after :host. So here, we check if .input-focus is present on the host element, then we apply the styling, otherwise not.

Now we only need to apply .input-focus class to the host element when input.focus is true, we can do this easily by @HostBinding:

  @HostBinding('class.input-focus')
get isInputFocus() {
return this.input ? this.input.focus : false;
}

------

component:

import {Component, Input, ContentChild, AfterContentInit, HostBinding} from '@angular/core';
import {InputRefDirective} from 'app/lib/common/input-ref.directive'; @Component({
selector: 'au-fa-input',
templateUrl: './au-fa-input.component.html',
styleUrls: ['./au-fa-input.component.css']
})
export class AuFaInputComponent implements AfterContentInit { @Input()
icon: string; @ContentChild(InputRefDirective)
input: InputRefDirective; @HostBinding('class.input-focus')
get isInputFocus() {
return this.input ? this.input.focus : false;
} ngAfterContentInit() {
if (!this.input) {
console.error('You forgot pass in the input field');
}
} get classes() { const cssClasses = {}; if (this.icon) {
cssClasses['fa-' + this.icon] = true;
} return cssClasses;
} }

Directive:

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

@Directive({
selector: 'au-fa-input input'
})
export class InputRefDirective { focus = false; @HostListener('focus')
isFocus() {
this.focus = true;
} @HostListener('blur')
isBlur() {
this.focus = false;
}
}

[Angular] @ContentChild with Directive ref的更多相关文章

  1. angular Creating a Directive that Adds Event Listeners

    <span my-draggable>Drag ME</span> angular.module('dragModule', []) .directive('myDraggab ...

  2. Angular 下的 directive (part 2)

    ngCloak ngCloak指令被使用在,阻止angular模板从浏览器加载的时候出现闪烁的时候.使用它可以避免闪烁问题的出现.   该指令可以应用于<body>元素,但首选使用多个ng ...

  3. angular 自定义指令 directive transclude 理解

    项目中断断续续的用了下angular,也没狠下心 认真的学习.angular 特别是自定义指令这块 空白. transclude 定义是否将当前元素的内容转移到模板中.看解释有点抽象. 看解释有点抽象 ...

  4. Angular自定义指令directive:scope属性

    在AngularJS中,除了内置指令如ng-click等,我们还可以自定义指令.自定义指令,是为了扩展DOM元素的功能.代码中,通过指定directive中的restrict属性,来决定这个指令是作为 ...

  5. Angular之指令Directive系列

    项目筹备近期开启Angular学习,指令比较难理解所以记录备案,推荐Angualr实战学习视频大漠穷秋 Angular实战 一.指令directive概述 指令可以对元素绑定事件监听或者改变DOM结构 ...

  6. angular插件制作——Directive指令使用详解

    1.replace——最简单的使用方法,直接将自定义标签替换为模板内的内容:  html: <!DOCTYPE html> <html> <head> <me ...

  7. Angular 下的 directive (part 1)

    directive  指令 Directive components  指令部分   使用指令自动引导一个AngularJS应用.ngApp指令指定应用程序的根元素,通常是放在页面的根元素如: < ...

  8. Angular ContentChild

    contentchild // 使用方法 git clone https://git.oschina.net/mumu-osc/learn-component.git cd learn-compone ...

  9. angular之自定义 directive

    1,指令的创建至少需要一个带有@Directive装饰器修饰的控制器类.@Directive装饰器指定了一个选择器名称,用于指出与此指令相关联的属性的名字. 2,创建一个highlight.direc ...

随机推荐

  1. seq---生成随机数

    seq命令用于产生从某个数到另外一个数之间的所有整数. 语法 seq [选项]... 尾数 seq [选项]... 首数 尾数 seq [选项]... 首数 增量 尾数 选项 -f, --format ...

  2. 【Codeforces Round #426 (Div. 2) C】The Meaningless Game

    [Link]:http://codeforces.com/contest/834/problem/C [Description] 有一个两人游戏游戏; 游戏包括多轮,每一轮都有一个数字k,赢的人把自己 ...

  3. ArcGIS Api For Flex 动态画点和线

    <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="ht ...

  4. hdu5400Arithmetic Sequence

    //一个序列,两个公差d1,d2 //问有多少个区间使得这个区间存在一个点,它的左边是公差为d1的序列 //它的右边是公差为d2的序列 //直接存入每一个点向左和向右延伸的公差长度,乘一下即可 //还 ...

  5. Drupal 关于节点(nodes)的理解

    在 Drupal 构建的站点中.全部的内容都是以节点形式存储的,一个节点能够是公布的不论什么一个内容,比方说一个单面(page).一个投票(Poll).一篇文章(article).论坛主题(forum ...

  6. [LuoguP4892]GodFly的寻宝之旅 状压DP

    链接 基础状压DP,预处理出sum,按照题意模拟即可 复杂度 \(O(n^22^n)\) #include<bits/stdc++.h> #define REP(i,a,b) for(in ...

  7. 1.lombok系列1:初识lombok

    转自:https://www.imooc.com/article/18156 初识lombok 官网:https://projectlombok.org/ 什么是lombok 连官网都懒得废话,只给出 ...

  8. [NPM] Update published npm packages using np

    When we want to update our package we need to do a few things: pull latest from our git remote, bump ...

  9. [Phonegap+Sencha Touch] 移动开发76 让cordova app訪问远端站点也能调用cordova插件功能

    原文链接:http://blog.csdn.net/lovelyelfpop/article/details/50735395 我相信.应该会有一些cordova开发人员想过实现以下这种app: 使用 ...

  10. HDU 3131 One…Two…Five! (暴力搜索)

    题目链接:pid=3131">HDU 3131 One-Two-Five! (暴力搜索) 题意:给出一串数字,要求用加,减,乘,除(5/2=2)连接(计算无优先级:5+3*6=8*6= ...