【问题标题】:Reactive binding of HTML with RxJSHTML 与 RxJS 的反应式绑定
【发布时间】:2020-04-30 20:48:57
【问题描述】:

在 Angular 应用程序的上下文中,我正在寻找一种反应式方法来将 html 与 rxjs observables 绑定。 这是一个虚拟示例:

import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, Observable, combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: `
    <input
      type="checkbox"
      [checked]="check1$ | async"
      (click)="check1$.next(!check1$.getValue())"
    />
    <input
      type="checkbox"
      [checked]="check2$ | async"
      (click)="check2$.next(!check2$.getValue())"
    />
    <p>status : {{ status$ | async }}</p>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  check1$ = new BehaviorSubject(true);
  check2$ = new BehaviorSubject(true);

  status$ = combineLatest([this.check1$, this.check2$]).pipe(
    map(([c1, c2]) => {
      return `${c1}, ${c2}`;
    }),
  );
}

请问你有什么意见?

非常感谢分享最佳做法

【问题讨论】:

标签: angular data-binding rxjs reactive


【解决方案1】:

用反应形式,思考

import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: `
    <form [formGroup]="form">
      <input type="checkbox" formControlName="check1" />
      <input type="checkbox" formControlName="check2" />
      <p>status : {{ check$ | async }}</p>
    </form>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  form = new FormGroup({
    check1: new FormControl(true),
    check2: new FormControl(false),
  });

  check$ = this.form.valueChanges.pipe(
    map(({ check1, check2 }) => `${check1}, ${check2}`),
  );
}

【讨论】:

    猜你喜欢
    • 2014-10-09
    • 1970-01-01
    • 2023-03-12
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    相关资源
    最近更新 更多