总和值输入ngFor /反应形式

时间:2019-07-14 04:58:55

标签: angular typescript

如何获得一个输入字段中两个值的总和并将结果存储在另一个输入字段中?

类似这样的事情: enter image description here

换句话说,这两个值value1value2已经带有* ngFor了,但是我不能进行加法,而且当任何一个值改变时,结果也会被修改。

component.html

<mat-form-field appearance="outline" class="col-md-3">
  <mat-label>Precio regular</mat-label>
  <input matInput type="number" formControlName="precioRegular" value="{{paquete.precio}}" (change)="updateTotal(paquete.precio)">
</mat-form-field>
<mat-form-field appearance="outline" class="col-md-3">
  <mat-label>Descuento</mat-label>
  <input matInput type="number" formControlName="descuento" value="{{paquete.descuento}}" (change)="updateTotal(paquete.descuento)">
  </mat-form-field>
<mat-form-field appearance="outline" class="col-md-3">
  <mat-label>Precio Final</mat-label>
  <input matInput formControlName="precioFinal" [value]="total">
</mat-form-field>

component.ts

  total: number;

  this.forma = this.fb.group({
    precioRegular: [  ],
    descuento: [  ],
    precioFinal: [ ],
  });


 updateTotal(item) {
    if (item) {
      this.total += item.value;
    } else {
      this.total -= item.value;
    }
    // console.log(this.total);
  }

4 个答案:

答案 0 :(得分:1)

您可以订阅反应式表单的更改并使用表单值执行一些操作。

例如:

onCreate

答案 1 :(得分:1)

正如我所说,这不是使用反应式表单的理想用例。通常,当您具有适当的数据模型并且想要围绕它构建表单时,或者要根据该数据模型获取表单的值时,通常会使用反应式表单。

在当前情况下,仅使用import SwiftUI import AVKit import PhotosUI import MobileCoreServices struct ContentView: View { @State var showImagePicker: Bool = false @State var url: URL? var body: some View { ZStack { VStack { Button(action: { withAnimation { self.showImagePicker.toggle() } }) { Text("Show image picker") } PlayerContainerView(player: AVPlayer(url: url ?? URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")!)) } if (showImagePicker) { ImagePicker(isShown: $showImagePicker, url: $url) } } } } struct PlayerView: UIViewRepresentable { let player: AVPlayer func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PlayerView>) { (uiView as? PlayerUIView)?.updatePlayer(player: player) } func makeUIView(context: Context) -> UIView { return PlayerUIView(player: player) } } class PlayerUIView: UIView { private let playerLayer = AVPlayerLayer() init(player: AVPlayer) { super.init(frame: .zero) playerLayer.player = player layer.addSublayer(playerLayer) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() playerLayer.frame = bounds } func updatePlayer(player: AVPlayer) { self.playerLayer.player = player } } struct PlayerContainerView : View { @State var seekPos = 0.0 private let player: AVPlayer init(player: AVPlayer) { self.player = player } var body: some View { VStack { PlayerView(player: player) PlayerControlsView(player: player) } } } struct PlayerControlsView : View { @State var playerPaused = true @State var seekPos = 0.0 let player: AVPlayer var body: some View { HStack { Button(action: { self.playerPaused.toggle() if self.playerPaused { self.player.pause() } else { self.player.play() } }) { Image(systemName: playerPaused ? "play" : "pause") .padding(.leading, 20) .padding(.trailing, 20) } Slider(value: $seekPos, from: 0, through: 1, onEditingChanged: { _ in guard let item = self.player.currentItem else { return } let targetTime = self.seekPos * item.duration.seconds self.player.seek(to: CMTime(seconds: targetTime, preferredTimescale: 600)) }) .padding(.trailing, 20) } } } struct ImagePicker: UIViewControllerRepresentable { @Binding var isShown: Bool @Binding var url: URL? class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @Binding var isShown: Bool @Binding var url: URL? init(isShown: Binding<Bool>, url: Binding<URL?>) { _isShown = isShown _url = url } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) guard let mediaType = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.mediaType)] as? String, mediaType == (kUTTypeMovie as String), let uiURL = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.mediaURL)] as? URL else { return } url = uiURL isShown = false } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { isShown = false } } func makeCoordinator() -> Coordinator { return Coordinator(isShown: $isShown, url: $url) } func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController { let picker = UIImagePickerController() picker.mediaTypes = [kUTTypeMovie as String] picker.delegate = context.coordinator return picker } func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) { } } fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue } #if DEBUG struct ContentView_Previews : PreviewProvider { static var previews: some View { ContentView(showImagePicker: true) } } #endif 会更好。

在这里,尝试一下:

[(ngModel)]

在您的模板中:

<div>
  <mat-form-field appearance="outline" class="col-md-3">
    <mat-label>Precio regular</mat-label>
    <input matInput type="number" [(ngModel)]="model.precioRegular">
  </mat-form-field>
  <mat-form-field appearance="outline" class="col-md-3">
    <mat-label>Descuento</mat-label>
    <input matInput type="number" [(ngModel)]="model.descuento">
  </mat-form-field>
  <mat-form-field appearance="outline" class="col-md-3">
    <mat-label>Precio Final</mat-label>
    <input matInput type="number" [value]="model.precioRegular + model.descuento">
  </mat-form-field>
</div>
  

这是您推荐的Working Sample StackBlitz

答案 2 :(得分:1)

您可以订阅表单中的所有更改,并将值加在一起。

this.forma.valueChanges.subscribe(value => { const sum = value.precioRegular + valuee.descuento; this.forma.get('precioFinal').setValue(sum); });

答案 3 :(得分:0)

  updateTotal(item) {
    if (item) {
      this.total += item.value;
    } else {
      this.total -= item.value;
    }
    this.forma.get('precioFinal').setValue(this.total);
  }

您也可以使用patchValue代替setValue来更改单个formCtrl的值。有关更多信息,请参见documentation

我希望能解决您的问题:)

相关问题