angular 10 直接获取表单值

Fork Me On Github

angular 10 直接获取表单值

在一些情况下只需要简单的获取表单的值,而不需要做一些不必要的值定义

例如:

  1. 列表的搜索框,

当然可以一个一个的值进行定义,通过绑定

public keywords = '';
<input [(ngModel)]="keywords">

但这种情况值是始终保持和输入一直,但并不能同时保持和搜索结果的条件一直。

这时我想到了直接获取搜索表单

<form (ngSubmit)="tapSearch(searchForm.value)" #searchForm="ngForm">
    <div class="input-group">
        <label for="keywords">标题</label>
        <input type="text" class="form-control" name="keywords" ngModel id="keywords" placeholder="搜索标题" [value]="keywords">
    </div>
    <button type="submit" class="btn btn-primary">搜索</button>
</form>
public keywords = '';

public tapSearch(form: any) {
    this.keywords = form.keywords || '';
    // TODO
}

这里需要注意

(ngSubmit)="tapSearch(searchForm.value)" #searchForm="ngForm"

#searchForm="ngForm" 是获取表单对象

<input name="keywords" ngModel [value]="keywords">

ngModel 进行绑定键值,必须的,不然在 searchForm.value 中无法获取到值

searchForm.value 的具体值为

{
    keywords: ''
}
Click here to view
Tags: angular
0 428 0
在 angular 项目中实现对页面的访问控制
按下回车键,焦点移动到下一个表单或提交表单
使用ng-template 显示tree结构数据
使用 ViewContainerRef.createComponent 替代 ComponentFactoryResolver
angular 12使用 KaTex 显示 AsciiMath 格式的公式