@angular/core#forwardRef TypeScript Examples

The following examples show how to use @angular/core#forwardRef. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: radio-button.component.ts    From canopy with Apache License 2.0 6 votes vote down vote up
constructor(
    @Self() @Optional() public control: NgControl,
    @Inject(forwardRef(() => LgRadioGroupComponent))
    private radioGroup: LgRadioGroupComponent,
    private errorState: LgErrorStateMatcher,
    @Optional()
    @Host()
    @SkipSelf()
    private controlContainer: FormGroupDirective,
    private renderer: Renderer2,
    private hostElement: ElementRef,
    private domService: LgDomService,
  ) {}
Example #2
Source File: suggestion.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
constructor(
    private readonly cdr: ChangeDetectorRef,
    @Inject(forwardRef(() => AutocompleteComponent))
    autocomplete: any, // FIXME: workaround temporarily
  ) {
    this.autocomplete = autocomplete;
    this.selected$ = combineLatest([
      this.autocomplete.directive$$.pipe(
        switchMap(directive => directive.inputValue$),
      ),
      this.value$$,
    ]).pipe(
      map(([inputValue, selfValue]) => inputValue === selfValue),
      tap(selected => {
        this.selected = selected;
      }),
      publishRef(),
    );
    this.visible$ = combineLatest([
      this.autocomplete.directive$$.pipe(
        switchMap(directive => directive.filterFn$),
      ),
      this.autocomplete.directive$$.pipe(
        switchMap(directive => directive.inputValue$),
      ),
      this.value$$,
    ]).pipe(
      map(([filterFn, filterString, suggestion]) =>
        filterFn(filterString, suggestion),
      ),
      tap(visible => {
        this.visible = visible;
      }),
      publishRef(),
    );
  }
Example #3
Source File: app-instance.component.ts    From angular-dream-stack with MIT License 6 votes vote down vote up
@Component({
  selector: 'angular-dream-app-instance',
  templateUrl: './app-instance.component.html',
  styleUrls: ['./app-instance.component.scss'],
  viewProviders: [
    {
      provide: AppInstance,
      useExisting: forwardRef(() => AppInstanceComponent),
    },
  ],
})
export class AppInstanceComponent implements AppInstance {
  @Input() appRegistration: AppRegistration;
  @Input() id: string;
  @Output() removeApp = new EventEmitter<void>();

  constructor(readonly injector: Injector) {}
}
Example #4
Source File: index.ts    From ui-pager with Apache License 2.0 6 votes vote down vote up
@Component({
    selector: 'Pager',
    template: ` <DetachedContainer>
        <Placeholder #loader></Placeholder>
    </DetachedContainer>`,
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [
        {
            provide: TEMPLATED_ITEMS_COMPONENT,
            useExisting: forwardRef(() => PagerComponent)
        }
    ]
})
export class PagerComponent extends TemplatedItemsComponent {
    public get nativeElement(): Pager {
        return this.templatedItemsView;
    }

    protected templatedItemsView: Pager;

    constructor(_elementRef: ElementRef, _iterableDiffers: IterableDiffers) {
        super(_elementRef, _iterableDiffers);
    }
}
Example #5
Source File: arc-to.ts    From canvas with MIT License 6 votes vote down vote up
@Directive({
    selector: 'canvas-arc-to',
    providers: [
        {
            provide: CANVAS_METHOD,
            useExisting: forwardRef(() => ArcToDirective),
        },
    ],
})
export class ArcToDirective implements CanvasMethod {
    @Input()
    x1 = 0;

    @Input()
    y1 = 0;

    @Input()
    x2 = 0;

    @Input()
    y2 = 0;

    @Input()
    radius = 0;

    call(context: CanvasRenderingContext2D) {
        context.arcTo(this.x1, this.y1, this.x2, this.y2, this.radius);
    }
}
Example #6
Source File: mood-radio.component.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
@Component({
  selector: 'app-mood-radio',
  templateUrl: './mood-radio.component.html',
  styleUrls: ['./mood-radio.component.scss'],
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => MoodRadioComponent),
    multi: true
  }]
})
export class MoodRadioComponent implements ControlValueAccessor {
  private _value: Mood;

  set value(value: Mood) {
    this._value = value;
    this.onValueChange(value);
  }

  get value(): Mood {
    return this._value;
  }

  readonly mood: typeof Mood = Mood;

  constructor() { }

  private onValueChange(value: Mood) { }

  writeValue(value: Mood): void {
    this._value = value;
  }

  registerOnChange(fn: SafeAny): void {
    this.onValueChange = fn;
  }

  registerOnTouched(fn: SafeAny): void { }
}
Example #7
Source File: checkbox-value-accessor.directive.ts    From s-libs with MIT License 6 votes vote down vote up
/** @hidden */
@Directive({
  selector: 'input[type=checkbox][nasModel]',
  // eslint-disable-next-line @angular-eslint/no-host-metadata-property
  host: {
    '(change)': 'onChange($event.target.checked)',
    '(blur)': 'onTouched()',
  },
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CheckboxValueAccessorDirective),
      multi: true,
    },
  ],
})
export class CheckboxValueAccessorDirective extends CheckboxControlValueAccessor {}
Example #8
Source File: index.ts    From nativescript-plugins with Apache License 2.0 6 votes vote down vote up
@Component({
  selector: 'Accordion',
  template: `
    <DetachedContainer>
      <Placeholder #loader></Placeholder>
    </DetachedContainer>`,
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{provide: ACCORDION_ITEMS_COMPONENT, useExisting: forwardRef(() => AccordionComponent)}]
})
export class AccordionComponent extends AccordionItemsComponent {

  public get nativeElement(): Accordion {
    return this.accordionItemsView;
  }

  protected accordionItemsView: Accordion;

  constructor(_elementRef: ElementRef,
              _iterableDiffers: IterableDiffers) {
    super(_elementRef, _iterableDiffers);
  }
}
Example #9
Source File: input.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputComponent),
      multi: true
    }
  ]
})
export class InputComponent implements OnInit, ControlValueAccessor {

  @Input() mask = '';
  @Input() disabled = false;
  @Input() title = 'Input';
  @Input() type: 'text' | 'number' | 'password' = 'text';
  @Input() placeholder = 'Write here...';
  @Input() mode: 'dark' | 'light' = 'dark';
  @Input() iconPath?: string;

  @Output() enter: EventEmitter<InputEvent> = new EventEmitter<InputEvent>();

  value = '';

  control = new FormControl('');

  onChange: (quantity: any) => void = (quantity) => {};

  onTouched: () => void = () => {};

  ngOnInit(): void {
  }

  onInput(value: any): void {
    this.writeValue(this.control.value);
    this.onTouched();
    this.onChange(this.control.value);
  }

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

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

  writeValue(value: any): void {
    if (!!value) {
      this.control.setValue(value);
      this.value = value;
    } else {
      this.value = '';
    }
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  onEnter(event: any): void {
    this.enter.emit(event);
  }

}
Example #10
Source File: accordion.component.ts    From canopy with Apache License 2.0 5 votes vote down vote up
@ContentChildren(forwardRef(() => LgAccordionPanelHeadingComponent), {
    descendants: true,
  })
  panelHeadings: QueryList<LgAccordionPanelHeadingComponent>;
Example #11
Source File: rating.component.ts    From Angular-Cookbook with MIT License 5 votes vote down vote up
@Component({
  selector: 'app-rating',
  templateUrl: './rating.component.html',
  styleUrls: ['./rating.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => RatingComponent),
      multi: true,
    },
  ],
})
export class RatingComponent implements OnInit, ControlValueAccessor {
  value = 2;
  hoveredRating = 2;
  isMouseOver = false;
  @Input() disabled = false;

  constructor() {}

  onChange: any = () => {};
  onTouched: any = () => {};

  ngOnInit(): void {}
  onRatingMouseEnter(rating: number) {
    if (this.disabled) return;
    this.hoveredRating = rating;
    this.isMouseOver = true;
  }
  onRatingMouseLeave() {
    this.hoveredRating = null;
    this.isMouseOver = false;
  }

  selectRating(rating: number) {
    if (this.disabled) return;
    this.value = rating;
    this.onChange(rating);
  }

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

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

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  writeValue(value: number) {
    this.value = value;
  }
}
Example #12
Source File: password-input.component.ts    From ReCapProject-Frontend with MIT License 5 votes vote down vote up
@Component({
  selector: 'app-password-input',
  templateUrl: './password-input.component.html',
  styleUrls: ['./password-input.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PasswordInputComponent),
      multi: true,
    },
  ],
  host: {
    '(change)': 'onChange($event.target.value)',
    '(input)': 'onChange($event.target.value)',
    '(blur)': 'onTouched()',
  },
})
export class PasswordInputComponent implements OnInit, ControlValueAccessor {
  @Input() id: string = 'password-input';
  @Input() label: string = 'Enter your password';
  @Input() invalidFeedback: string = 'Please enter your password.';
  passwordHidden: boolean = true;
  value: string = '';
  onChange: any = () => {};
  onTouched: any = () => {};
  disabled = false;

  @Input() errors: any;
  @Input() touched: any;
  @Input() dirty: any;

  constructor() {}

  ngOnInit(): void {}

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

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

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

  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  togglePasswordHidden() {
    this.passwordHidden = !this.passwordHidden;
  }

  isPasswordHidden(): string {
    return this.passwordHidden ? 'password' : 'text';
  }

  isPasswordHiddenIcon(): string {
    return this.passwordHidden ? 'fa-eye-slash' : 'fa-eye text-primary';
  }
}
Example #13
Source File: validation-message.component.ts    From ngx-admin-dotnet-starter with MIT License 5 votes vote down vote up
@Component({
  selector: 'ngx-validation-message',
  styleUrls: ['./validation-message.component.scss'],
  template: `
      <div class="warning">
          <span class="caption status-danger"
             *ngIf="showMinLength"> Min {{ label }} length is {{ minLength }} symbols </span>
          <span class="caption status-danger"
             *ngIf="showMaxLength"> Max {{ label }} length is {{ maxLength }} symbols </span>
          <span class="caption status-danger" *ngIf="showPattern"> Incorrect {{ label }} </span>
          <span class="caption status-danger" *ngIf="showRequired"> {{ label }} is required</span>
          <span class="caption status-danger" *ngIf="showMin">Min value of {{ label }} is {{ min }}</span>
          <span class="caption status-danger" *ngIf="showMax">Max value of {{ label }} is {{ max }}</span>
      </div>
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NgxValidationMessageComponent),
      multi: true,
    },
  ],
})
export class NgxValidationMessageComponent {
  @Input()
  label: string = '';

  @Input()
  showRequired?: boolean;

  @Input()
  min?: number;

  @Input()
  showMin?: boolean;

  @Input()
  max?: number;

  @Input()
  showMax: boolean;

  @Input()
  minLength?: number;

  @Input()
  showMinLength?: boolean;

  @Input()
  maxLength?: number;

  @Input()
  showMaxLength?: boolean;

  @Input()
  showPattern?: boolean;
}
Example #14
Source File: suggestion-group.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
@ContentChildren(forwardRef(() => SuggestionComponent))
  suggestions: QueryList<SuggestionComponent>;
Example #15
Source File: fy-select-vehicle.component.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
@Component({
  selector: 'app-fy-select-vehicle',
  templateUrl: './fy-select-vehicle.component.html',
  styleUrls: ['./fy-select-vehicle.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => FySelectVehicleComponent),
      multi: true,
    },
  ],
})
export class FySelectVehicleComponent implements OnInit, ControlValueAccessor {
  @Input() mandatory = false;

  @Input() label = 'Type';

  @Input() isAmountDisabled = false;

  @Input() mileageConfig;

  private ngControl: NgControl;

  private innerValue;

  get valid() {
    if (this.ngControl.touched) {
      return this.ngControl.valid;
    } else {
      return true;
    }
  }

  private onTouchedCallback: () => void = noop;

  private onChangeCallback: (_: any) => void = noop;

  constructor(private injector: Injector) {}

  ngOnInit() {
    this.ngControl = this.injector.get(NgControl);
  }

  get value(): any {
    return this.innerValue;
  }

  set value(v: any) {
    if (v !== this.innerValue) {
      this.innerValue = v;

      this.onChangeCallback(v);
    }
  }

  onBlur() {
    this.onTouchedCallback();
  }

  writeValue(value: any): void {
    if (value !== this.innerValue) {
      this.innerValue = value;
    }
  }

  selectType(value: string) {
    this.value = value;
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }
}
Example #16
Source File: color-input.component.ts    From angular-material-components with MIT License 5 votes vote down vote up
MAT_COLORPICKER_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => NgxMatColorPickerInput),
  multi: true
}
Example #17
Source File: calendar.ts    From ngx-mat-datetime-picker with MIT License 5 votes vote down vote up
constructor(private _intl: MatDatepickerIntl,
    @Inject(forwardRef(() => NgxMatCalendar)) public calendar: NgxMatCalendar<D>,
    @Optional() private _dateAdapter: NgxMatDateAdapter<D>,
    @Optional() @Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats,
    changeDetectorRef: ChangeDetectorRef) {

    this.calendar.stateChanges.subscribe(() => changeDetectorRef.markForCheck());
  }
Example #18
Source File: tour-anchor.directive.ts    From ngx-ui-tour with MIT License 5 votes vote down vote up
@Directive({
    selector: '[tourAnchor]',
    providers: [
        TuiDropdownDirective,
        TuiParentsScrollService,
        {
            provide: TUI_DROPDOWN_DIRECTIVE,
            useExisting: forwardRef(() => TuiDropdownDirective)
        }
    ]
})
export class TourAnchorTuiDropdownDirective implements OnInit, OnDestroy, TourAnchorDirective {

    @Input()
    tourAnchor: string;

    @HostBinding('class.touranchor--is-active')
    isActive: boolean;

    constructor(
        private readonly tourService: TourTuiDropdownService,
        private readonly tourBackdropService: TourBackdropService,
        private readonly tourStepTemplateService: TourStepTemplateService,
        private readonly tuiDropdown: TuiDropdownDirective,
        private elementRef: ElementRef
    ) {}

    ngOnInit(): void {
        this.tourService.register(this.tourAnchor, this);
    }

    public ngOnDestroy(): void {
        this.tourService.unregister(this.tourAnchor);
    }

    showTourStep(step: ITuiDdStepOption) {
        const htmlElement: HTMLElement = this.elementRef.nativeElement,
            templateComponent = this.tourStepTemplateService.templateComponent;

        templateComponent.step = step;
        this.isActive = true;

        if (!step.disableScrollToAnchor) {
            ScrollingUtil.ensureVisible(htmlElement);
        }

        if (step.placement?.horizontalDirection)
            this.tuiDropdown.align = step.placement.horizontalDirection;
        if (step.placement?.verticalDirection)
            this.tuiDropdown.direction = step.placement.verticalDirection;
        this.tuiDropdown.limitMinWidth = 'auto';
        this.tuiDropdown.minHeight = 170;
        this.tuiDropdown.content = templateComponent.template;

        if (step.enableBackdrop) {
            this.tourBackdropService.show(this.elementRef);
        } else {
            this.tourBackdropService.close();
        }

        step.prevBtnTitle = step.prevBtnTitle || 'Prev';
        step.nextBtnTitle = step.nextBtnTitle || 'Next';
        step.endBtnTitle = step.endBtnTitle || 'End';

        this.tuiDropdown.open = true;
    }

    hideTourStep() {
        this.isActive = false;
        this.tuiDropdown.open = false;

        if (this.tourService.getStatus() === TourState.OFF) {
            this.tourBackdropService.close();
        }
    }

}
Example #19
Source File: task-manage-form.component.ts    From ng-ant-admin with MIT License 5 votes vote down vote up
EXE_COUNTER_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  multi: true,
  useExisting: forwardRef(() => TaskManageFormComponent)
}
Example #20
Source File: knob.ts    From EDA with GNU Affero General Public License v3.0 5 votes vote down vote up
KNOB_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => Knob),
    multi: true
}
Example #21
Source File: markdown.component.ts    From ng-util with MIT License 5 votes vote down vote up
@Component({
  selector: 'nu-markdown',
  template: ``,
  exportAs: 'nuMarkdown',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NuMarkdownComponent),
      multi: true,
    },
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NuMarkdownComponent extends NuMarkdownBaseComponent implements ControlValueAccessor {
  private onChange = (_: string) => {};

  protected init(): void {
    this.ngZone.runOutsideAngular(() => {
      const options = {
        value: this._value,
        cache: {
          enable: false,
        },
        mode: 'sv',
        minHeight: 350,
        input: (value: string) => {
          this.ngZone.run(() => {
            this._value = value;
            this.onChange(value);
          });
        },
        ...this.config?.defaultOptions,
        ...this.options,
      };
      this._instance = new Vditor(this.el.nativeElement, options);
      this.ngZone.run(() => this.ready.emit(this._instance));
    });
  }

  private setDisabled(): void {
    if (!this.instance) {
      return;
    }
    if (this.disabled) {
      this.instance.disabled();
    } else {
      this.instance.enable();
    }
  }

  writeValue(value: string): void {
    this._value = value || '';
    if (this.instance) {
      this.instance.setValue(this._value);
    }
  }

  registerOnChange(fn: (_: string) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(_: () => void): void {}

  setDisabledState(_isDisabled: boolean): void {
    this.disabled = _isDisabled;
    this.setDisabled();
  }
}
Example #22
Source File: ellipse.ts    From canvas with MIT License 5 votes vote down vote up
@Directive({
    selector: 'canvas-ellipse',
    providers: [
        {
            provide: CANVAS_METHOD,
            useExisting: forwardRef(() => EllipseDirective),
        },
    ],
})
export class EllipseDirective implements CanvasMethod {
    @Input()
    x = 0;

    @Input()
    y = 0;

    @Input()
    radiusX = 0;

    @Input()
    radiusY = 0;

    @Input()
    rotation = 0;

    @Input()
    startAngle = 0;

    @Input()
    endAngle = 0;

    @Input()
    anticlockwise = false;

    call(context: CanvasRenderingContext2D) {
        context.ellipse(
            this.x,
            this.y,
            this.radiusX,
            this.radiusY,
            this.rotation,
            this.startAngle,
            this.endAngle,
            this.anticlockwise,
        );
    }
}
Example #23
Source File: account-select.component.ts    From digital-bank-ui with Mozilla Public License 2.0 5 votes vote down vote up
@Component({
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => AccountSelectComponent), multi: true }],
  selector: 'ngx-account-select',
  templateUrl: './account-select.component.html',
})
export class AccountSelectComponent implements ControlValueAccessor, OnInit {
  formControl: FormControl;

  @Input() title: string;

  @Input() required: boolean;

  @Input() type: AccountType;

  accounts: Observable<Account[]>;

  _onTouchedCallback: () => void = noop;

  private _onChangeCallback: (_: any) => void = noop;

  constructor(private accountingService: AccountingService) {}

  ngOnInit(): void {
    this.formControl = new FormControl('');

    this.accounts = this.formControl.valueChanges.pipe(
      distinctUntilChanged(),
      debounceTime(500),
      tap(name => this.changeValue(name)),
      filter(name => name),
      switchMap(name => this.onSearch(name)),
    );
  }

  changeValue(value: string): void {
    this._onChangeCallback(value);
  }

  writeValue(value: any): void {
    this.formControl.setValue(value);
  }

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

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

  setDisabledState(isDisabled: boolean): void {
    if (isDisabled) {
      this.formControl.disable();
    } else {
      this.formControl.enable();
    }
  }

  onSearch(searchTerm?: string): Observable<Account[]> {
    const fetchRequest: FetchRequest = {
      page: {
        pageIndex: 0,
        size: 5,
      },
      searchTerm: searchTerm,
    };

    return this.accountingService.fetchAccounts(fetchRequest, this.type).pipe(map((accountPage: AccountPage) => accountPage.accounts));
  }

}
Example #24
Source File: boolean-input.component.ts    From radiopanel with GNU General Public License v3.0 5 votes vote down vote up
@Component({
	selector: 'app-boolean-input',
	templateUrl: './boolean-input.component.html',
	providers: [
		{
			provide: [],
			useExisting: forwardRef(() => BooleanInputComponent),
			multi: true,
		},
	],
})
export class BooleanInputComponent implements OnInit, OnDestroy, ControlValueAccessor {
	@Input() label?: string;
	@Input() mode: InputMode = InputMode.EDIT;

	private componentDestroyed$: Subject<boolean> = new Subject<boolean>();

	public inputMode = InputMode;
	public control: FormControl = new FormControl(false);
	public updateValue = (_: any) => {};

	constructor(public ngControl: NgControl) {
		ngControl.valueAccessor = this;
	}

	private propagateChange(value: any): void {
		if (this.updateValue) {
			return this.updateValue(value);
		}

		if (this.control) {
			this.control.setValue(value);
		}
	}

	public ngOnInit() {
		this.control.valueChanges.pipe(
			takeUntil(this.componentDestroyed$),
		).subscribe((value) => {
			this.propagateChange(value);
		});
	}

	public ngOnDestroy() {
		this.componentDestroyed$.next(true);
		this.componentDestroyed$.complete();
	}

	public writeValue(value: any) {
		setTimeout(() => this.control.setValue(value));
	}

	public registerOnChange(fn: any) {
		this.updateValue = fn;
	}

	public registerOnTouched() {}
}
Example #25
Source File: date-picker.ts    From sba-angular with MIT License 5 votes vote down vote up
DATE_PICKER_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => BsDatePicker),
    multi: true
}
Example #26
Source File: checkbox_value_accessor.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
@ContentChildren(forwardRef(() => CheckboxControl), { descendants: true })
  children!: QueryList<CheckboxControl>;
Example #27
Source File: ngx-colors-trigger.directive.ts    From ngx-colors with MIT License 4 votes vote down vote up
@Directive({
  selector: "[ngx-colors-trigger]",
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NgxColorsTriggerDirective),
      multi: true,
    },
  ],
})
export class NgxColorsTriggerDirective implements ControlValueAccessor {
  //Main input/output of the color picker
  // @Input() color = '#000000';
  // @Output() colorChange:EventEmitter<string> = new EventEmitter<string>();

  color = "";

  //This defines the type of animation for the palatte.(slide-in | popup)
  @Input() colorsAnimation: "slide-in" | "popup" = "slide-in";

  //This is used to set a custom palette of colors in the panel;
  @Input() palette: Array<string> | Array<NgxColor>;

  @Input() format: string;
  @Input() position: "top" | "bottom" = "bottom";
  @Input() hideTextInput: boolean;
  @Input() hideColorPicker: boolean;
  @Input() attachTo: string | undefined = undefined;
  @Input() overlayClassName: string | undefined = undefined;
  @Input() colorPickerControls: "default" | "only-alpha" | "no-alpha" =
    "default";
  @Input() acceptLabel: string = "ACCEPT";
  @Input() cancelLabel: string = "CANCEL";
  // This event is trigger every time the selected color change
  @Output() change: EventEmitter<string> = new EventEmitter<string>();
  // This event is trigger every time the user change the color using the panel
  @Output() input: EventEmitter<string> = new EventEmitter<string>();
  // This event is trigger every time the user change the color using the panel
  @Output() slider: EventEmitter<string> = new EventEmitter<string>();

  @HostListener("click") onClick() {
    this.open();
  }
  constructor(
    private triggerRef: ElementRef,
    private panelFactory: PanelFactoryService
  ) {}

  panelRef: ComponentRef<PanelComponent>;
  isDisabled: boolean = false;

  onTouchedCallback: () => void = () => {};
  onChangeCallback: (_: any) => void = () => {};

  open() {
    if (!this.isDisabled) {
      this.panelRef = this.panelFactory.createPanel(
        this.attachTo,
        this.overlayClassName
      );
      this.panelRef.instance.iniciate(
        this,
        this.triggerRef,
        this.color,
        this.palette,
        this.colorsAnimation,
        this.format,
        this.hideTextInput,
        this.hideColorPicker,
        this.acceptLabel,
        this.cancelLabel,
        this.colorPickerControls,
        this.position
      );
    }
  }

  public close() {
    this.panelFactory.removePanel();
  }

  public onChange() {
    this.onChangeCallback(this.color);
  }

  public setDisabledState(isDisabled: boolean): void {
    this.isDisabled = isDisabled;
    this.triggerRef.nativeElement.style.opacity = isDisabled ? 0.5 : undefined;
  }

  public setColor(color) {
    this.writeValue(color);
    this.input.emit(color);
  }

  public sliderChange(color) {
    this.slider.emit(color);
  }

  get value(): string {
    return this.color;
  }

  set value(value: string) {
    this.setColor(value);
    this.onChangeCallback(value);
  }

  writeValue(value) {
    if (value !== this.color) {
      this.color = value;
      this.onChange();
      this.change.emit(value);
    }
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }
}
Example #28
Source File: quantity-input.component.ts    From nghacks with MIT License 4 votes vote down vote up
@Component({
  selector: 'quantity-input',
  templateUrl: './quantity-input.component.html',
  styleUrls: ['./quantity-input.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => QuantityInputComponent),
      multi: true
    }
  ]
})
export class QuantityInputComponent implements ControlValueAccessor, OnDestroy {

  quantityCtrl = new FormControl(1);

  @Input() color: string;

  limit = 10000000;
  @Input('limit')
  private set limitValue(v: string) {
    if (!v) { return; }
    this.limit = parseInt(v);
  }

  // Allow the input to be disabled, and when it is make it somewhat transparent.
  disabled = false;
  @Input('disabled')
  private set disabledValue(v: boolean) {
    if (!v) { return; }
    this.quantityCtrl.disable();
    this.disabled = v;
  }

  private _unsubscribeAll: Subject<any> = new Subject();

  @Output() quantityChange = new EventEmitter<number>();

  // Function to call when the quantity changes.
  onChange = (quantity: number) => {
    this.quantityChange.emit(quantity);
  }

  // Function to call when the input is touched (when a star is clicked).
  onTouched = () => { };
  get value(): number {
    return this.quantityCtrl.value;
  }

  constructor() {
    this.quantityCtrl.valueChanges
      .pipe(
        takeUntil(this._unsubscribeAll)
      )
      .subscribe((val) => {
        if (this.quantityCtrl.value < 1) {
          this.writeValue(1);
        }
        else if (this.quantityCtrl.value > this.limit) {
          this.writeValue(this.limit);
        }
        else {
          this.writeValue(this.quantityCtrl.value);
        }
      });
  }

  increase(): void {
    if (!this.disabled) {
      this.quantityCtrl.setValue((this.quantityCtrl.value + 1));
    }
  }

  decrease(): void {
    if (!this.disabled) {
      this.quantityCtrl.setValue((this.quantityCtrl.value - 1));
    }
  }

  // Allows Angular to update the model (quantity).
  // Update the model and changes needed for the view here.
  writeValue(quantity: number): void {
    this.quantityCtrl.setValue(quantity, { emitEvent: false });
    this.onChange(this.value);
  }

  // Allows Angular to register a function to call when the model (quantity) changes.
  // Save the function as a property to call later here.
  registerOnChange(fn: (quantity: number) => void): void {
    this.onChange = fn;
  }

  // Allows Angular to register a function to call when the input has been touched.
  // Save the function as a property to call later here.
  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  // Allows Angular to disable the input.
  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
    if (isDisabled) {
      this.quantityCtrl.disable();
    }
    else {
      this.quantityCtrl.enable();
    }
  }

  public ngOnDestroy(): void {
    this._unsubscribeAll.next();
    this._unsubscribeAll.complete();
  }

}
Example #29
Source File: checkbox.component.ts    From alauda-ui with MIT License 4 votes vote down vote up
@Component({
  selector: 'aui-checkbox',
  templateUrl: './checkbox.component.html',
  styleUrls: ['./checkbox.component.scss'],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  preserveWhitespaces: false,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CheckboxComponent),
      multi: true,
    },
  ],
})
export class CheckboxComponent<T>
  extends CommonFormControl<boolean>
  implements AfterViewInit, OnDestroy
{
  id = `aui-checkbox-${uniqueId++}`;

  @Input()
  name = '';

  @Input()
  type = 'label';

  @Input()
  get label() {
    return this._label;
  }

  set label(val) {
    this._label = val;
    this.label$$.next(val);
  }

  @Input()
  get indeterminate(): boolean {
    return this._indeterminate;
  }

  set indeterminate(value: boolean) {
    this._indeterminate = value;
  }

  @ViewChild('elRef', { static: true })
  elRef: ElementRef;

  private readonly checkboxGroup: CheckboxGroupComponent<T>;
  private _label: T;
  private readonly label$$ = new BehaviorSubject(this.label);
  private _indeterminate = false;
  private readonly destroy$$ = new Subject<void>();

  constructor(
    cdr: ChangeDetectorRef,
    @Optional()
    @Inject(forwardRef(() => CheckboxGroupComponent))
    checkboxGroup: CheckboxGroupComponent<T>,
    private readonly focusMonitor: FocusMonitor,
  ) {
    super(cdr);
    this.checkboxGroup = checkboxGroup;
    if (this.checkboxGroup) {
      combineLatest([this.checkboxGroup.model$, this.label$$])
        .pipe(
          takeUntil(this.destroy$$),
          map(([values, label]) => {
            if (this.checkboxGroup.trackFn) {
              return values?.some(
                v =>
                  this.checkboxGroup.trackFn(v) ===
                  this.checkboxGroup.trackFn(label),
              );
            }
            return values?.includes(label);
          }),
        )
        .subscribe(checked => {
          this.writeValue(!!checked);
        });
    }
  }

  ngAfterViewInit() {
    this.focusMonitor.monitor(this.elRef.nativeElement, true);
  }

  ngOnDestroy() {
    this.destroy$$.next();
    this.focusMonitor.stopMonitoring(this.elRef.nativeElement);
  }

  onClick() {
    if (this.disabled) {
      return;
    }
    if (this.indeterminate) {
      this._indeterminate = false;
    }
    this.emitValue(!this.model);
    if (this.checkboxGroup) {
      this.checkboxGroup.onCheckboxChange(this);
    }
  }

  onBlur() {
    if (this.onTouched) {
      this.onTouched();
    }
    if (this.checkboxGroup) {
      this.checkboxGroup.onCheckboxBlur();
    }
  }
}