我正在使用 Angular 開發 Ionic 應用程式并遇到以下錯誤:
my.page.ts(片段)
export class MyPage implements OnInit {
public myArray: Array<string> = [];
constructor(){}
ngOnInit(){
this.updateArray();
}
updateArray() {
// Performs API Call and puts the results into 'myArray'
}
}
my.page.html(片段)
<ion-select interface="popover">
<ion-select-option *ngFor="let item of myArray">{{item}}</ion-select-option>
</ion-select>
我期望的是,陣列中包含的字串被映射到“離子選擇”的選擇選項。但是,我的瀏覽器控制臺顯示錯誤NG0303: Can't bind to 'ngForOf' since it isn't a known property of 'ion-select-option'
在研究該錯誤時,我只能找到item of myArray不應再使用的 ngFor ( 等) 的舊用法。但是,據我所知,我已經使用了最新的語法。
我正在使用 運行我的應用程式npx ionic serve --lab,使用版本 6 的 Ionic 和版本 13 的 Angular。
我還嘗試了不同的組件,例如“ion-text”,但發生了同樣的錯誤。
此外,我通過在 http-request 完成后列印來驗證來自 API-Call 的資料是否正確存盤在陣列中。
我究竟做錯了什么?
提前致謝!
更新:
這是我的 my.app.module 檔案:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { MyPageRoutingModule } from './my-routing.module';
import { MyPage } from './my.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
MyPageRoutingModule
],
declarations: [MyPage]
})
export class MyPageModule {}
uj5u.com熱心網友回復:
當您使用目標元素中不存在的屬性或在這種情況下類似的屬性時,可能會發生此型別錯誤Can't bind to 'something' since it isn't a known property of 'element',因為您嘗試使用無法找到的屬性指令。在這種情況下,您嘗試使用ngForOf指令但找不到它,因此您必須確保在組件的主機模塊中匯入該指令的主機模塊。CommonModule要解決這種情況,您必須在您這樣宣告的模塊中匯入MyPage。
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [MyPage, ...],
imports: [CommonModule, ...]
})
編輯
分配一個valuefor很重要,<ion-select-option>因為默認值為undefined. 我能夠在stackblitz上重現您的問題,并且在未分配value.
uj5u.com熱心網友回復:
您需要呼叫 ngIf 以確保在您的 myArray 資料準備好之前未加載資料。
將您的 HTML 代碼更改為下面以檢查您的陣列中是否存在任何資料,如果沒有,它將保持隱藏和不活動狀態,直到有資料。
<ion-select *ngIf="myArray.length > 0" interface="popover">
<ion-select-option *ngFor="let item of myArray">{{item}}</ion-select-option>
</ion-select>
uj5u.com熱心網友回復:
我只是想提供一個簡短的更新!
最終,這個問題并不是真正與 Angular/Ionic 相關的。相反,問題在于我撰寫的用于更新陣列的函式是傳統函式,而不是箭頭函式。
因此,“this”屬于不同的背景關系,因此通過覆寫系結 UI 的陣列,實際上創建了一個新變數。
因此,UI 不受更改的影響。將函式更改為箭頭函式解決了這個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/481822.html
上一篇:IonicV6-一旦使用ng-if過濾,離子段顯示卡片之間的空白過多
下一篇:如何阻止滑鼠右鍵單擊iframe
