typescript - วิธีเรียกฟังก์ชันใน <ng-template> การประกาศตัวแปร let Angular 4
ฉันมีฟังก์ชันที่ส่งค่ากลับเป็นสี สีของข้อความ และวันที่จากฟังก์ชัน TypeScript เป็นอ็อบเจกต์ ซึ่งฉันต้องการเก็บไว้ในตัวแปร let ฉันสามารถเรียกใช้ฟังก์ชันโดยตรงได้ แต่ไม่ต้องการเรียกใช้ฟังก์ชันซ้ำ
นี่ทำให้ฉันเกิดข้อผิดพลาดเหมือนกับว่า 'year' ไม่พบ
<kendo-grid-column-group title="{{year}}" [headerStyle]="{'text-align': 'center'}" width="380">
<ul *ngFor="let month of keys(); let i = index">
<li>
<kendo-grid-column field="{{month}}" class="no-padding" title="{{month}}" [filterable]="false" [sortable]="false" width="35">
<ng-template kendoGridCellTemplate let-dataItem let-color="getColor(year,i,dataItem.ca)">
<span class="whole-cell" [ngStyle]="{'background-color': color.color,'color': color.textColor,'font-weight':'bold','height':'25px','vertical-align': 'middle'}">
<label>{{color.Date}}</label>
</span>
</ng-template>
</kendo-grid-column>
</li>
</ul>
</kendo-grid-column-group>
คำตอบ #1
คุณต้องส่งออบเจ็กต์สโคป 'content:this'
แม่แบบ:
<ng-template let-color="getColor()" #loading>
<span class="whole-cell" [ngStyle]="{'background-color': color.color,'color': color.textColor,'font-weight':'bold','height':'25px','vertical-align': 'middle'}">
<label>{{color.Date}}</label>
</span>
</ng-template>
<ng-container *ngTemplateOutlet="loading;context:this"></ng-container>
ส่วนประกอบ:
getColor() {
return {
color: 'red',
textColor: 'blue',
Date: 'hi'
}
}
คำตอบ #2
หนึ่งในเทคนิคที่สามารถใช้ได้คือการใช้งาน *ngIf ผิดวิธี (ตรวจสอบเวอร์ชันของ Angular ที่รองรับมันด้วย)
<ng-container *ngIf="{color:getColor(year,i,dataItem.ca)}; let state">
{{state.color.Date}}
</ng-container>
- *ngIf ช่วยให้เก็บผลลัพธ์ของนิพจน์ในตัวแปรได้
- เนื่องจากมีการสร้างวัตถุขึ้นมา, *ngIf จะเป็นจริงเสมอ ดังนั้นจึงจะแสดง ng-container
- ng-container จะไม่ถูกแสดงเป็นองค์ประกอบ DOM จะมีแค่เนื้อหาของมันเท่านั้น
