如何在angular2中获得形式的声音

时间:2017-05-29 05:15:53

标签: angular angular2-forms

如何从表单中获取值。我试过以下代码:

class EncounterDetailViewController: UIViewController {

    // MARK: - Outlets
    @IBOutlet weak var encounterDateLabel: UILabel!
    @IBOutlet weak var locationLabel: UILabel!
    @IBOutlet weak var lengthLabel: UILabel!
    @IBOutlet weak var contributorNameLabel: UILabel!
    @IBOutlet weak var contributorImageView: UIImageView!

    // MARK: - Properties
    var selectedEncounter: Encounter?

    // MARK: - View did load
    override func viewDidLoad() {
        super.viewDidLoad()
        //access selectedEncounter property here and set all label's text
    }
}

2 个答案:

答案 0 :(得分:3)

您需要在表单中使用name个属性,以及与ngModel绑定,这些Angular可以跟踪输入元素并将其与表单控件相关联。

<input type="text" placeholder="username" name="username" ngModel>
<input type="password" placeholder="password" name="password" ngModel>

如果没有这些,您的表单对象将只是一个空对象。

<强> DEMO

答案 1 :(得分:3)

你应该这样做

<form #f="ngForm" (ngSubmit)="onLogin(f.value)">
    <input type="text" placeholder="username" name="username" ngModel>
    <input type="password" placeholder="password" name="password" ngModel>
    <button type="submit">Submit</button>    
</form>

并且

onLogin(f){
    console.log("username :"+f.username,"password :"+f.password);
}