选择值编号乘以反应形式

时间:2019-06-11 14:17:02

标签: angular typescript

我试图将选择垫的值乘以另一个已经建立的垫,例如scrollToView,其中A x B是固定数字,而A是一个会发生变化的垫选择。

然后将该乘法的结果保存到反应形式的另一个字段中。

到目前为止,我已经尝试过了,但是乘法的结果并没有改变,如果我在mat-select中进行了更改,则总是B应该改变:

component.ts

1380

component.html

precio: 690
selectedPersona = 2;
numeroPersonasTotal: any;

ngOnInit() {
  this.forma = this.fb.group ({
    numeroPersonas: [ this.selectedPersona ],
    precioPersona: [ this.precioPersona() ],
    totalPrecio: [ this.totalPrecio()],
  });

  this.numeroPersonasTotal = [ 1, 2, 3, 4, 5, 6, 7 ];
  console.log(this.precio, this.selectedPersona);
}

totalPrecio() {
  return this.precio * this.selectedPersona;
}

guardarReserva() {
  this.fs.saveReserva(this.forma.value);
  console.log(this.forma.value);
}

2 个答案:

答案 0 :(得分:0)

这是我要操纵值时用于反应式的解决方案。我将尽力而为,因为您的ReactiveForm格式有点令人困惑。

创建一个方法调用onChanges()。在此函数内部,您将需要订阅表单的值更改,并将表单数据即数据传递给您用来操纵值的函数。

onChanges() {
   this.forma.valueChanges.subscribe(data => {
      this.totalPrecio(data);
   });
}

然后我们将要更改totalPrecio()

totalPrecio(data) {
    return this.precio * data.numeroPersonas;
}

然后最后确保我们在ngOnInit()中调用此函数

ngOnInit() {
   this.onChanges();
}

答案 1 :(得分:0)

您可以实现onChanges()或将$event传递给totalPrecio()

实现onChanges()是最佳实践选项: https://angular.io/guide/lifecycle-hooks#onchanges

如果要坚持使用当前格式,则可以传递$event。 (类似于这个问题:onchange equivalent in angular2

添加一个字段以保存总计(我选择将其命名为totalPrecioN): 我还注意到precio: number = 690缺少';'。

precio: number = 690; // missing ';' above
selectedPersona = 2;
totalPrecioN: number = 0;

我已经从表单中删除了mat-,但这显示了如何传递它:

  <form [formGroup]="forma">
        <select [value]="selectedPersona"
                formControlName="numeroPersonas" 
                (ngModelChange)="totalPrecio($event)">
          <option *ngFor="let persona of numeroPersonasTotal" [value]="persona">
            {{ persona }}
          </option>
        </select>


      <div>
        <span>Precio por persona</span>
        <span>USD - {{precio}}</span>
    </div>
    <hr>
    <div>
        <span>Total</span>
        <span>USD - {{totalPrecioN}}</span>
    </div>
  </form>

接下来,更改totalPrecio以使用传入的值:

  totalPrecio(selectedPersonaN: number) {
    console.log(selectedPersonaN); // if you want to see the value change
    this.totalPrecioN = this.precio * selectedPersonaN;
  }

我在StackBlitz上放了一个版本,展示了如何传递$ event:https://stackblitz.com/edit/angular-abb2ux

顶部为当前版本,底部为$event。 我更改了一些内容以仅显示表单。