typescript Angular 错误类型错误:无法读取null的属性(正在读取"_rawValidators")

pu82cl6c  于 2022-12-27  发布在  TypeScript
关注(0)|答案(2)|浏览(246)

i具有以下Angular 代码,并得到错误TypeError:无法读取null的属性(正在读取"_rawValidators")

import { Component, OnInit } from '@angular/core';
import { Wifi } from './wifi';
import { WifiService } from './wifi.service';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'angular-esp';

  datalist: Array<Wifi> = [];
  wifiSelected : Wifi = {} as Wifi;
  psk = "";
  ssid = "";

  
  checkoutForm = this.formBuilder.group({
    ssid: [''],
    psk: ['']
  });
  
  constructor(private wifiservice: WifiService, private formBuilder: FormBuilder) { }

  ngOnInit()
  {
    this.wifiservice.getWifiList().subscribe(wifilist => this.datalist = wifilist);
  }

  selected(){
    this.ssid = this.wifiSelected.ssid;
  }

  onSubmit(): void {
    this.wifiservice.connect(this.checkoutForm.value).subscribe();
  }
}

跟随html:

<form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">

<div class="section">
  <select [(ngModel)]="wifiSelected" (select)="selected()">
    <option *ngFor="let item of this.datalist"  [ngValue]="item">{{item.ssid}}</option>
  </select>
</div>
<div>
  <input type="text" [(ngModel)]="ssid" formControlName="ssid">
</div>
<div [hidden]="wifiSelected.auth == 'WIFI_AUTH_OPEN'">
  <input type="password" name="psk" [(ngModel)]="psk" formControlName="psk">
</div>
<div><button class="button" type="submit">connect</button></div>
</form>
<div>
  {{wifiSelected | json}}
</div>

在页面加载时,我得到错误"错误类型错误:无法读取null的属性(正在读取"_rawValidators")"。
有什么建议吗?
如果我评论formgroup的部分,它会起作用。

bogh5gae

bogh5gae1#

不要在表单中同时使用ngModel和表单控件。不建议在表单组中使用ngModel(模板驱动方法)(被动方法)。如果你改变了它,希望它能解决这个问题。

6mw9ycah

6mw9ycah2#

当我在我的IDE中尝试你的代码时,我实际上得到了一个不同的错误,告诉我不应该在窗体中使用ngModel。然后我更改了html代码,错误消失了。我认为你仍然需要为你的select-form-control添加一个formControlName

<form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">

    <div class="section">
      <select (select)="selected()">
        <option *ngFor="let item of this.datalist"  [ngValue]="item">{{item.ssid}}</option>
      </select>
    </div>
    <div>
      <input type="text" formControlName="ssid">
    </div>
    <div [hidden]="wifiSelected.auth == 'WIFI_AUTH_OPEN'">
      <input type="password" name="psk" formControlName="psk">
    </div>
    <div><button class="button" type="submit">connect</button></div>
    </form>
    <div>
      {{wifiSelected | json}}
</div>

相关问题