[英]display the map value if key exists in angular 5 html
在component
文件中創建了 map - tempDAMap
:
import 'rxjs/add/operator/map';
export class AComponent implements OnInit {
tempDAMap = new Map();
/** Onchange */
selectedName(pName: any): void {
this.service.getPAData(pName).subscribe( (data) => {
if (data.length > 0 && data != '' && data != null) {
this.savedData = data;
this.tempDataStatus = true;
this.savedData.forEach(function(assessData) {
this.tempDAMap.set(assessData.qId, assessData.ansSelected);
})
}
else {
this.tempDataStatus = false;
}
},
(error) => {} )
}
}
在 HTML 文件中,有一個包含QuestionId
的外部 for 循環,並在 map(子集)內檢查QuestionId
是否存在於其中並顯示來自 map tempDAMap
的值。
<div *ngFor="let QA of Questions">
<div> <label> {{ques.desc}} </label>
<div *ngIf="tempDataStatus === true">
/** Check if tempDAMap contains Id (from Questions- outer for loop)*/
<div *ngIf="tempDAMap.has(ques.questionId)">
<p> {{ }} </p> /** display the map value */
</div>
</div>
</div>
</div>
我無法檢查密鑰是否存在並顯示 map 值。
錯誤:TypeError:無法讀取未定義的屬性“tempDAMap”。
請幫我。
代替:
this.savedData.forEach(function(assessData) {
this.tempDAMap.set(assessData.qId, assessData.ansSelected);
});
您需要使用箭頭功能:
this.savedData.forEach((assessData) => {
this.tempDAMap.set(assessData.qId, assessData.ansSelected);
});
In javascript, function
is a keyword that represents an action but it also has similar behavior to the class
keyword , playing the role of a class constructor when it appears after another keyword: new (eg. new function(...) {...}
)。 最初這甚至是在 javascript 中實例化對象的方式。
Because of that, when you use the function
keyword you set a scope, and the this
inside it refers to the function itself, as a consequence of its class constructor behavior.
可以通過以下兩種方式之一避免上述行為:
that
是用於此任務的通用變量名稱):const that = this;
this.savedData.forEach(function(assessData) {
that.tempDAMap.set(assessData.qId, assessData.ansSelected);
});
this
的含義,您可以在創建 function 時避免使用function
關鍵字。 取而代之的是,您可以使用箭頭 function表示法(其他編程語言中的lambda 函數)來定義您的函數。 By doing that the this
keyword inside the body of the arrow function will refer to the outside scope (some people like to say that you bring the outside scope to the function scope ).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.