19 December 2017

ControlValueAccessor TwoWay Binding trong Angular 2+

 ControlValueAccessor TwoWay Binding

interface ControlValueAccessor {
  writeValue(obj: any): void;
  registerOnChange(fn: any): void;
  registerOnTouched(fn: any): void;
  setDisabledState?(isDisabled: boolean): void;
}

Step 1

import {
  ControlValueAccessor,
  NG_VALUE_ACCESSOR
} from '@angular/forms';

Step 2

export const MY_APP_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => AppComponent),
  multi: true
};

Step 3

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MY_APP_VALUE_ACCESSOR]
})
export class AppComponent implements ControlValueAccessor {
}

Step 4

export class AppComponent implements ControlValueAccessor {

  value: string;
  @Input() disable: boolean;

  onModelChange: Function = () => { };
  onModelTouched: Function = () => { };

  writeValue(obj: any): void { this.value = obj; }
  registerOnChange(fn: any): void { this.onModelChange = fn; }
  registerOnTouched(fn: any): void { this.onModelTouched = fn; }
  setDisabledState?(val: boolean): void { this.disable = val; }

}

Read

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

Write

onClick(event: Event): void {
    this.onModelChange(this.value);
}

ng-touched ng-untouched

onBlur(value: any): void {
    this.onModelTouched();
}

disabled

new FormControl({value:'', disable.true};)

Demo



Related Posts:

  • :CSS pseudo-class host ::ng-deep :host-context() /deep/ >>> Styling in Angular 2+ :host ::ng-deep Thứ tự các component lồng nhau theo mũi tên xuống ::ng-deep /* Đặt ở bất kỳ component đều có màu đỏ */ /* Toàn bộ thẻ p ở các component có màu đỏ - nó mang tính tổng thể */ ::ng-deep p { color: red… Read More
  • Cách sử dụng @input và @output trong Angular 2+ Bước 1: Tạo project Angular 2 với cmd bấm vào đây Bước 2: Tạo component ng generate component input-output Tạo component thành công Cấu trức thư mục được tạo Component đã được tự động khai báo trong app.modul… Read More
  • Deploying an Angular App to Github Pages angular-cli-ghpages Deploying an Angular App to Github Pages Installation & Setup npm i angular-cli-ghpages --save-dev Usage Usage: 1, ng build --prod --base-href "https://<user-name>.github.io/<repositor… Read More
  • Guards Routes Angular 2+ 1. Guard Types Có bốn loại guards khác nhau chúng ta có thể sử dụng để bảo về routes của mình: CanActivate: Quyết định việc một route được kich hoạt. CanActivateChild: Quyết định việc children routes được kich hoạt … Read More
  • Uncaught Error: Template parse errors is not a known element compiler.js: 2547 Uncaught Error: Template parse errors: 'app-login-box' is not a known element: 1. If 'app-login-box' is an Angular component, then verify that it is part of this module. 2. If 'app-login-box' is … Read More

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang