类型错误:无法读取 null 的属性(读取"写入值")



我试图通过id获取对象,但如果该对象不存在,组件将注册该对象。

但是当对象存在时,它会正常获取该对象并再次抛出此错误

HTML:

<div class="card shadow-sm m-5 p-5 bg-light" style="min-width: 60%; max-width: 70%">
<mat-toolbar>{{(veiculo && veiculo.id)?'Editar Veiculo':'Cadastrar Veiculo'}}</mat-toolbar>

<div class="card-body">
<div class="form-group" *ngIf="veiculo.id != null">
<label class="form-label">ID</label>
<input type="text" class="form-control" [(ngModel)]="veiculo.id" readonly />
</div>
<div class="form-group">
<label class="form-label">Placa Oeste</label>
<input type="text" class="form-control" [(ngModel)]="veiculo.placaOeste" />
</div>
<div class="form-group">
<label class="form-label">Modelo</label>
<input type="text" class="form-control" [(ngModel)]="veiculo.modelo">
</div>
<div class="form-group">
<label class="form-label">Marca</label>
<input type="text" class="form-control" [(ngModel)]="veiculo.marca">
</div>
<div class="form-group">
<label class="form-label">Ano</label>
<input type="text" class="form-control" [(ngModel)]="veiculo.ano">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input">
<label class="form-check-label" [(ngModel)]="veiculo.portariaSEJUSP">Deriva da Portaria SEJUSP/DGPC nº
133/2018</label>
</div>

<div>
<button class="btn btn-primary m-2" (click)="salvar()">
Salvar
</button>
<button type="button" class="btn btn-warning mx-2" routerLink="/veiculos">
Cancelar
</button>
</div>
</div>

TS:

export class VeiculoCadastrarEditarComponent implements OnInit {
veiculoForm!: FormGroup;
veiculo = new Veiculo();
id: any = 0;
constructor(
private service: VeiculoService,
private router: Router,
private activatedRoute: ActivatedRoute
) {}
ngOnInit(): void {
this.id = this.activatedRoute.snapshot.paramMap.get('id');
if (this.id) {
this.service.pesquisarPorId(this.id).subscribe({
next: (data) => (this.veiculo = data),
error: (err) => console.log(err),
});
}
}
salvar() {
if (this.veiculo && this.veiculo.id) {
this.service
.atualizar(this.veiculoForm.value, this.veiculo.id)
.subscribe({
next: () => this.router.navigateByUrl('/veiculos'),
// error: () => this.onErrorEdicao(),
});
} else {
this.service.cadastrar(this.veiculoForm.value).subscribe({
next: () => this.router.navigateByUrl('/veiculos'),
// error: () => this.onErrorCadastro(),
});
}
}
deletar() {
this.service.deletar(this.veiculoForm.value).subscribe({
next: () => this.router.navigateByUrl('/veiculos'),
// error: () => this.onErrorDelete(),
});
}
}

信息:

Angular CLI: 14.0.5节点:16.14.2包管理器:npm 8.5.0操作系统:win32 x64

编辑:

我发现错误在html复选框中,当我把它拿出来的时候错误消失了,但是我需要它,我怎么解决它?

复选框的属性为boolean

我猜错误是- [(ngModel)]应该在input标签中给出,而不是在label标签中。

相关内容

  • 没有找到相关文章

最新更新