angular 如何實現ng-model

最近在用angular5寫項目,剛接觸angular,他對於我還是陌生的朋友,最近寫了一個組件 用到了ng-model的實現,所以這裏簡單記錄下

比如要創建一個組件叫my-input

1首先 

在@Component配置中添加encapsulation的配置,它有三個值分別是

ViewEncapsulation.None:沒有Shadow Dom,樣式沒有封裝,全局可以使用。

ViewEncapsulation.Emulated:angular2的默認值,模仿ShadowDom,通過在標籤上增加標識,來固定樣式的作用域

ViewEncapsulation.Native:使用原生的Shadow Dom

一般使用默認值ViewEncapsulation.Emulated

2 配置providers

providers:[{

    provide:NG_VALUE_ACCESSOR,

    useExisting:forwardRef(()=>{MyInputComponent}) ,//這裏是組件的名字

    multi:true

}]

//@Component完整代碼
@Component({
   selector:'app-my-input',
   templateUrl:'./my-input.component.html',
   styleUrls:['./my-input.component.scss'],
   encapsulation:ViewEncapsulation.Emulated,
   providers:[{
     provide:NG_VALUE_ACCESSOR,
     useExisting:forwardRef(()=>MyInputComponent),
     multi:true
   }]
})

 3 MyINputComponent要實現ControValueAccessor這個接口

它有3個方法  writeValue(obj:any):void和registerOnChange(fn:any):void    registerOnTouched(fn:any):void要實現

實現了這三個方法基本就可以實現數據的輸出

數據的輸入是通過@Input data獲取的

export class MyInputComponent implements OnInit,ControlValue{
  @Input() data:string;

  onChange: any=Function.prototype;
  onTouched: any=Function.prototype;
 

  constructor(){}

  writeValue(obj:any):void{
     this.data = obj;
  }

  registerOnChange(fn:any):void{
     this.onChange=fn
  }

  registerOnTouched(fn:any):void{
     this.onTouch=fn
  }
//自定義方法   當數據改變的時候
  dataChange(){
     this.onChange(this.data)
  }

}

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章