在我的組件中,我有一個由父模塊填充的變數,該變數的欄位“描述”之一應該顯示在帶有兩種系結文本區域的 html 模板中,以便我可以對其進行編輯:
@Input() table: Table;
public tableDescription: String = this.table.description (does not compile)
上面的代碼無法編譯,我得到一個angular property is used before its initialization錯誤。我在模板中使用該變數的方式是:
<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>
我還嘗試在以下位置初始化該變數ngOnInit:
ngOnInit() {
this.tableDescription = this.table.description
}
但是雖然代碼編譯我看到:
- 警告指出
arg1:TypeError: Cannot read properties of undefined (reading 'description') - html 模板中的文本區域為空。
如何tableDescription使用 的值初始化組件中的變數table.description并將其顯示在 html 模板中?
uj5u.com熱心網友回復:
您必須至少將此分配移動到,ngOnInit()最好的方法是ngOnChanges對輸入更改做出反應。
@Input() table: Table;
public tableDescription:string;
ngOnChanges(changes:SimpleChanges){
if(changes.table){
this.tableDescription= this.table?.description;
}
}
uj5u.com熱心網友回復:
您必須知道何時@Input()更改以確保您已table設定屬性。
所以這是更好的解決方案,它僅在更改ngOnChanges時呼叫:@Input
@Input set table(value: Table) {
this.tableDescription = value?.description;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421058.html
標籤:
