I am trying to create a dynamic form-control, I want some controls to be disabled based on the condition, but I get Type error of undefined. here is my code for it.
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;
}
}
now if I don't use else condition and only if it doesn't give me an error but It only renders the disabled input fields.
this is my HTML code
<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>
I just want to create the input fields and some of them should be disabled because user don't have permission to change it, but it cant seems to create these fields and give me an error. the error is as follows,
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)
The temp1 variable may not be defined when you try to access it in the template. You could use the safe navigation operator ?. to workaround the error.
<mat-form-field *ngIf="temp1[i]?.name" appearance="outline" style="width: 95%;">
It checks if temp1[i] is defined before trying to access it's properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With