angular6 表单


 

表单提交

 

1)  form定义模板引用变量 #addlinkform = " ngForm "

2)  ngSubmit提交表单数据 刚才定义的模板引用变量 addlinkform.value为表单数据的值

3)表单项使用ngModel 包括input.select

 

 

 模板html内

<form #addlinkform="ngForm" (ngSubmit)="onsubmit(addlinkform.value)" >

  <div class="form-group">
    <label for="name">链接名称:</label>
    <input id="name" type="text" name="name"  ngModel>
  </div>



  <div class="form-group">
    <label for="address">链接地址:</label>
    <input id="address" type="text" name="address" ngModel>
  </div>



  <div class="form-group">
    <label for="description">链接描述:</label>
    <input id="description" type="text" name="description" ngModel>
  </div>


  <div class="form-group">
    <label for="tag">标签:</label>
    <input id="tag" type="text" name="tag" ngModel >
  </div>

  <div class="form-group">
    <label for="linkclass">分类:</label>

      <select name="linkclass" id="linkclass" ngModel>
          <option>分类1</option>
          <option>分类2</option>
          <option>分类3</option>
          <option>分类4</option>
      </select>
  </div>

  <button type="submit"  class="btn btn-success" [disabled]="!addlinkform.form.valid" >提交</button>
    <button class="btn btn-secondary" >返回</button>
</form>

 

组件内接收表单数据

1)接收表单值,ngSubmit触发的函数发送表单数据到组件内

模板引用变量 addlinkform的value值为表单数据

<form #addlinkform="ngForm" (ngSubmit)="onsubmit(addlinkform.value)" >

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-addsite',
  templateUrl: './addsite.component.html',
  styleUrls: ['./addsite.component.sass']
})
export class AddsiteComponent implements OnInit {

  constructor() { }

  value: any;

  onsubmit(data: any) {
    console.log(data)
     return this.value = data;
  }

  ngOnInit() {
  }

}

  

  

 

资料:

Angular表单处理

https://angular.cn/guide/forms#submit-the-form-with-emngsubmitem

强大的 Angular 表单验证

 

报错处理

1.ng: Can't bind to 'formGroup' since it isn't a known property of 'form'.

<form [formGroup]= 'addsiteform1' (ngSubmit)="onsubmit()"> formGroup一直报错

解决办法:

project1\src\app\app.module.ts 里添加 ReactiveFormsModule 模块

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM