in my component i have a variable which is populated by the parent module, one of this variable's field 'description' should be displayed in the html template with a two way binding textarea so i can edit it:
@Input() table: Table;
public tableDescription: String = this.table.description (does not compile)
The above code wont compile, i get a angular property is used before its initialization error.
The way i am using that variable in the template is:
<form >
<mat-form-field appearance="fill">
<textarea matInput style="resize: none;" rows="7" id="tableDescription" name="tableDescription" [(ngModel)]="tableDescription">{{tableDescription}}</textarea>
</mat-form-field>
<mat-button-toggle (click)="updateDescription()">Update description
</mat-button-toggle>
</form>
I have also tried to initialize that variable in ngOnInit:
ngOnInit() {
this.tableDescription = this.table.description
}
But although the code compiles i see:
- A warning stating that
arg1:TypeError: Cannot read properties of undefined (reading 'description') - The text area in the html template is empty.
How can i initialize the tableDescription variable in the component with the value of table.description and display it in the html template?
CodePudding user response:
You have to move this assignment to at least ngOnInit() and the best would be ngOnChanges to react to input changes.
@Input() table: Table;
public tableDescription:string;
ngOnChanges(changes:SimpleChanges){
if(changes.table){
this.tableDescription= this.table?.description;
}
}
CodePudding user response:
You have to know when @Input() is changed to be sured you have table property set.
So this is better solution to ngOnChanges, it invokes only on @Input changed:
@Input set table(value: Table) {
this.tableDescription = value?.description;
}
