角度指令カスタム命令は - 学ぶための簡単な方法を属性

1.カスタムコマンド - @directive

 

インポート{ コンポーネント指令HostListener ElementRef } から'@角度/コア'
@ 指令({
    セレクタ:「[入力トリム]」
    ホスト: {
        '(keyUpイベント') 'keyUpFunc($ event.target)'
        '(クリック)' 'のonClick($ event.target)'
        「役割-データ」「入力トリム」
    }
})
輸出クラスInputTrimDirective {
    プライベート_elementRef ElementRef
    constructor(_elementRef: ElementRef) {
        console.log(_elementRef, "获取挂载属性的DOM")
        this._elementRef = _elementRef
    }
    /**
     *  是属性装饰器,用来为宿主元素添加事件监,类似于我们原生JavaScript的addEventListener
        @HostListener这里我们监听了keyup事件(可以定义原生JavaScript中的其他事件),
        当表单中有输入的时候我们就会调用方法,传递了一个$event对象进去,后面紧跟我们触法keyup事件的方法体
        可以用 @Component 中的 host 代替
     * */
    // @HostListener('keyup', ['$event.target'])
    keyUpFunc(evt) {
        if(evt.value) {
            this._elementRef.nativeElement.value = evt.value + '_num'
        }
    }
    onClick(evt) {
        console.log(evt.innerHTML, "click_div")
        if(evt.innerHTML) {
            this._elementRef.nativeElement.innerHTML = evt.innerHTML + '_num'
        }
 

2. DOM 中使用 -- 属性方式使用

<div>
    <h1>指令---directive</h1>
    <input type="text" class="input_1" input-trim>
    <div class="click_div" input-trim>sasas</div>
    <input type="text" class="input_2" role-data='input-trim'>
</div>

3. 在根模块中引用

 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TemplateDirective } from './directive/template-directive.component'
// 指令
import { InputTrimDirective } from './directive/template-directive.component'
@NgModule({
  // 引入组件,指令
  declarations: [
    AppComponent,
    TemplateDirective,
    InputTrimDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

おすすめ

転載: www.cnblogs.com/monkey-K/p/11449528.html