gpt4 book ai didi

javascript - Angular 9 - 错误类型错误 : Cannot read property 'name' of undefined

转载 作者:行者123 更新时间:2023-12-04 00:56:46 31 4
gpt4 key购买 nike

我正在尝试创建一个动态表单控件,我希望根据条件禁用某些控件,但出现未定义的类型错误。这是我的代码。

ngOnInit(): void {

this.dynamicForm = this.formBuilder.group({
tickets: new FormArray([])
});
}
get f() { return this.dynamicForm.controls; }
get t() { return this.f.tickets as FormArray; }

itemClick(node) {

for (let i = 0 ; i < this.data_tree.length; i++) {
this.nestsort.push(Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(this.data_tree[i])))
var check
rights.forEach(element => {
if(element == this.temp[i].id)
{
check = false
}
else{
check = true;
}


});
this.t.push(this.formBuilder.group({
name: ({value: [this.nestsort[i][aisa]], disabled: check})

}));




this.temp1 = this.t.value;


}


}

现在如果我不使用 else 条件并且仅当它不给我错误但它只呈现禁用的输入字段时。

这是我的HTML代码

<div *ngFor="let ticket of t.controls; let i = index">
<div [formGroup]="ticket">
<div>
<mat-form-field *ngIf="temp1[i].name" appearance="outline" style="width: 95%;">
<mat-label>{{temp[i].id}} </mat-label>
<input matInput type="text" placeholder="Name" formControlName="name" class="form-control"/>
<!-- <mat-hint >Errors appear instantly!</mat-hint> -->
</mat-form-field>

我只想创建输入字段,其中一些应该被禁用,因为用户没有更改它的权限,但它似乎无法创建这些字段并给我一个错误。错误如下,

navbars.component.html:77 ERROR TypeError: Cannot read property 'name' of undefined
at Object.updateDirectives (navbars.component.html:79)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:46970)
at checkAndUpdateView (core.js:45981)
at callViewAction (core.js:46347)
at execEmbeddedViewsAction (core.js:46304)
at checkAndUpdateView (core.js:45982)
at callViewAction (core.js:46347)
at execEmbeddedViewsAction (core.js:46304)
at checkAndUpdateView (core.js:45982)
at callViewAction (core.js:46347)

最佳答案

当您尝试在模板中访问它时,temp1 变量可能未定义。你可以使用 safe navigation operator ?. 解决错误。

<mat-form-field *ngIf="temp1[i]?.name" appearance="outline"  style="width: 95%;">

它会在尝试访问它的属性之前检查是否定义了 temp1[i]

关于javascript - Angular 9 - 错误类型错误 : Cannot read property 'name' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61826291/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com