最简单的Angular 双向绑定

使用:


TS

import {Component, forwardRef, Input, OnInit} from '@angular/core'
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'
import {RadioGroupItem} from './radio-group-item'

const CUSTOM_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => RadioGroupComponent),
  multi: true
}

@Component({
  selector: 'app-radio-group',
  templateUrl: './radio-group.component.html',
  styleUrls: ['./radio-group.component.scss'],
  providers: [CUSTOM_VALUE_ACCESSOR]
})
export class RadioGroupComponent implements OnInit, ControlValueAccessor {

  private _value: RadioGroupItem = new RadioGroupItem()

  @Input() values = []

  @Input() labels = []

  @Input() name = 'radioGroup'

  onChange = (_) => {
  }

  onTouched = () => {
  }

  writeValue(obj: any): void {
    if (this._value !== obj) {
      this._value = obj
    }
  }

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

  registerOnTouched(fn: any): void {
    this.onTouched = fn
  }

  constructor() {
  }

  ngOnInit() {
  }

}

HTML

CSS/SCSS

ul {

  display: flex;

  li {
    flex-grow: 1;

    input[type=radio] {
      display: none;
    }

    label {
      display: block;
      margin: 0;
      text-align: center;
      padding: 1em 0;
      border: 1px solid #eeeeee;

      &.checked {
        border: 1px solid #127cc3;
      }
    }
  }
}

你可能感兴趣的:(最简单的Angular 双向绑定)