如何手动触发Angular 2输入验证?

时间:2017-06-26 11:45:37

标签: javascript angular typescript

我有两个输入: - 我应用自定义验证器的第一个 - 第二个我在自定义验证器中使用的值(它是动态的和可编辑的)

如果我在第一个输入上应用我的自定义验证器,那么我将关注第二个并更改值 - 我想强制第一个输入重新验证...

目前只有在我更改值时才会重新验证第一个输入...有什么建议吗?

当我关注第一个输入时,我可以访问它的参考:

            <input
              name="mEnd"
              class="form-control"
              [(ngModel)]="endDate"
              ...
              #endDateInput="ngModel"
              (focus)="clog(endDateInput)"
            >

我想知道我可以使用输入formControl引用方法触发重新验证吗?

3 个答案:

答案 0 :(得分:28)

您可以更新formControl的有效性

form.controls['myControl'].updateValueAndValidity();

答案 1 :(得分:0)

如果您具有模板驱动的表单,则可以访问表单抛出ViewChild装饰器:

@ViewChild('myForm') public form: NgForm;

然后,使用上述方法验证一个字段或整个表单组:

this.form.controls.myControl.updateValueAndValidity();

答案 2 :(得分:-3)

我发现这要好得多

import UIKit
import AVFoundation
import MediaPlayer

class ViewController: UIViewController, AVAudioPlayerDelegate {
    var myPlayer: AVAudioPlayer? = nil

    func loadSound(filename: NSString) -> AVAudioPlayer? {
        let url = Bundle.main.url(forResource: filename as String, withExtension: "mp3")
        do {
            let player = try AVAudioPlayer(contentsOf: url ?? URL(fileURLWithPath: ""))
            player.prepareToPlay()
            return player
        }
        catch {
            print("Error : \(error)")
            return nil
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        guard let testPlayer = loadSound(filename: "silence") else {
            print("Not able to load the sound")
            return
        }
        testPlayer.delegate = self
        testPlayer.volume = 0.8
        testPlayer.numberOfLoops = -1
        myPlayer = testPlayer
        myPlayer?.play()
    }


    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.becomeFirstResponder()
        UIApplication.shared.beginReceivingRemoteControlEvents()
    }

    override func remoteControlReceived(with event: UIEvent?) {
        let rc = event?.subtype
        print("rc.rawValue: \(rc?.rawValue)")
        // Do your thing
    }
}