使用ngModel创建组件

@angular/forms里有个接口用来实现支持[(ngModel)],具体可查ControlValueAccessor,这边还未深入理解只是为了开发组件而初步了解

interface ControlValueAccessor {
  writeValue(obj: any): void
  registerOnChange(fn: any): void
  registerOnTouched(fn: any): void
  
}

我们要做的事就是实现这个接口

import {NG_VALUE_ACCESSOR,ControlValueAccessor} from "@angular/forms"
@Component({
  selector: 'app-search-select',
  templateUrl: './search-select.component.html',
  styleUrls: ['./search-select.component.less'],
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => SearchSelectComponent),
    multi: true
  }]
})
  export class SearchSelectComponent implements ControlValueAccessor {
      writeValue(obj: any): void
      registerOnChange(fn: any): void
      registerOnTouched(fn: any): void
  }
 

 下面是我实现下拉框的子组件和父组件值的双向绑定,也很好的解释angular 的双向数据绑定是由属性绑定和方法绑定结合在一起的

export class SearchSelectComponent implements ControlValueAccessor {
  @Input() ngModel:string;
  @Output() ngModelChange=new EventEmitter<string>();
  @Input() options:Array<any>;

  private selectValue:string;
  private isShow:boolean;
  private selectList:Array<any>;

  constructor() {
    this.isShow=false;
  }

  ngOnChanges(){
    this.selectValue=this.ngModel;
    this.selectList=this.options;
  }
  registerOnChange(fn: any): void {
    // 页面值改变时,调用该方法,传入新值实现回传

  }

  registerOnTouched(fn: any): void {
    
  }
  ngOnInit() {
     
  }

   // 赋值时调用
   writeValue(val: object): void {
    
  }

  selectItem(value){
    this.ngModelChange.emit(value);
  }

  showSelectList(){
    this.isShow=true;
  }
  hideSelectList(){
    this.isShow=false;
  }
}
View Code

 

  

posted @ 2019-09-02 22:39  LLC-Mite  阅读(308)  评论(0编辑  收藏  举报