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