Angular FormGroup

Angular formgroup

最近升級 angular 13,發現有些變數型別定義變得更加嚴謹。

13~14 版本在控制 formgroup value errors 時,無法使用舊版方式定義,

angular any 這類的定義,其實很偷懶也很無言,因為這樣就跟 javascript 有何區別…

雖然快速,但卻往往有弊。

以上是抱怨…..。

版本 13 以下,簡約介紹

1
2
formGP:FormGroup; ngOnInit(): void { this.formGP = new FormGroup({ name: new
FormControl(null), age: new FormControl(null), }); }

版本 13~14

1
2
formGP:FormGroup; constructor() { this.formGP = new FormGroup({ name: new
FormControl(null), age: new FormControl(null), }); }

版本 13~14

1
2
formGP = new FormGroup({ name: new FormControl(null), age: new
FormControl(null), }); constructor() {} ngOnInit(): void {}

取得 FormGroup Value

1
2
3
4
5
6
7
formGP = new FormGroup({ name: new FormControl<string|null
>(null), age: new FormControl<number|null
>(null) }); constructor() {} ngOnInit(): void {} onSubmit():{
if(this.formGP.value.email){ console.log(this.formGP.value.name);✅
console.log(this.formGP.value.name.length);✅ } }</number|null
></string|null
>

14 版本依舊使用舊版

1
2
3
4
formGP = new UntypedFormGroup({ name: new UntypedFormControl(null), age: new
UntypedFormControl(null) }); constructor() {} ngOnInit(): void {} onSubmit():{
if(this.formGP.value.email){ console.log(this.formGP.value.name);✅
console.log(this.formGP.value.name.length);✅ } }

作者

Nigo Chen

發表於

2022-06-08

更新於

2022-06-08

許可協議

評論

© 2022

0個訪客