【问题标题】:How to set default form Value from Observable?如何从 Observable 设置默认表单值?
【发布时间】:2021-11-12 22:15:29
【问题描述】:

这是我的 ts 组件

export interface Product{
    id?:string,
    name:string,
    price:string;
    quantity:string;
    tags:Tags[];
    description:string;
    files: File[];
}

product$:Observable<Product | undefined>;

ngOnInit(): void { 
  this.store.dispatch(new productActions.LoadProduct(fromProduct.getCurrentProductId.toString()));
  this.product$ = this.store.pipe(select(fromProduct.getCurrentProduct));
}

最后一个和第二个语句收集产品可观察的价值并且工作正常。

this.product = this.fb.group({
    name:['',[
      Validators.required,
      Validators.minLength(1),
      Validators.maxLength(128)
    ]],
    price:['',
    Validators.required],
    tags:this.fb.array(this.tags),
    quantity:['',Validators.required],
    description:['',
    Validators.required]
  });
}

现在我想要的是从 Product$ (observable) 设置 Form 的默认值

上面的代码设置了 name '' 的默认值。但是我想从 (product$ | async).name----->> 设置一个默认值,这在 Html 中可以正常工作,但我不知道如何在打字稿中做到这一点。

谢谢你帮助我。

【问题讨论】:

    标签: angular typescript observable angular-reactive-forms


    【解决方案1】:

    您可以将整个 FormGroup 初始化放入订阅中。 不过不要忘记使用第一个运算符,因为您只想执行一次然后取消订阅。

    this.product$
        .pipe(first())
        .subscribe(product => {
            this.product = this.fb.group({
                name:[product.name,[
                  Validators.required,
                  Validators.minLength(1),
                  Validators.maxLength(128)
                ]],
                price:['',
                Validators.required],
                tags:this.fb.array(this.tags),
                quantity:['',Validators.required],
                description:['',
                Validators.required]
              });
            }
        });
    

    【讨论】:

      【解决方案2】:

      您需要订阅 observable,以便当有一个值传递时,您可以接收它并使用它做一些事情。大概是这样的:

      this.product$ = this.store.pipe(select(fromProduct.getCurrentProduct));
      this.product$.subscribe(valueFromSubscription => this.product.patchValue(...));
      

      【讨论】:

        猜你喜欢
        • 2010-10-10
        • 1970-01-01
        • 1970-01-01
        • 2019-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多