Submitting Forms (ngSubmit)

表单的一般完整写法:

如果表单验证失败,必须 disable 提交按钮,阻止用户提交不合法的数据。

提交表单后,与表单对应的 json 数据 post 到后端:

{

"id":1,

"name":"pikachu",

"type":"fire"

}

修改 HTML, pokemon-template-form.component.html:

Pokemon Name:

type="radio"

name="isCool"

[value]="true"

#pokemonName="ngModel"

[ngModel]="pokemon.isCool"

/>Pokemon is cool?

type="radio"

name="isCool"

[value]="false"

[ngModel]="pokemon.isCool"

(ngModelChange)="toggleIsCool($event)"

/>Pokemon is NOT cool?

type="checkbox"

name="acceptTerms"

[(ngModel)]="pokemon.acceptTerms"

/>

Accept Terms?

Pokemon Type:

MODEL: {{ pokemon | json }} FORM: {{ form.value | json }} ERROR:

NOT PRINSTINE ANYMORE IT IS DIRTY!

实现 handleSubmit,pokemon-template-form.component.html:

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

import { Pokemon, PokemonType } from '../models/pokemon';

import { PokemonService } from '../services/pokemon.service';

@Component({

selector: 'app-pokemon-template-form',

templateUrl: './pokemon-template-form.component.html',

styleUrls: ['./pokemon-template-form.component.css'],

})

export class PokemonTemplateFormComponent implements OnInit {

pokemon!: Pokemon;

// create dropdown for Pokemon type

pokemonType: PokemonType[] = [

{

key: 0,

value: 'Fire',

},

{

key: 1,

value: 'Water',

},

];

constructor(private pokemonService: PokemonService) {}

toggleIsCool(object: any) {

console.log(object);

this.pokemon.isCool = !this.pokemon.isCool;

}

ngOnInit() {

this.pokemonService.getPokemon(1).subscribe((data: Pokemon) => {

this.pokemon = data;

});

}

handleSubmit(object: any) {

console.log(object)

}

}

运行 ng serve,点击 save button, 从 console 可以看到表单被提交:

好文链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: