typescript - Angular2 ผูกข้อมูลโดยใช้ตัวดำเนินการเงื่อนไข
ฉันมีคำถามเกี่ยวกับการ binding ใน Angular2
ฉันเขียนคอมโพเนนต์ง่าย ๆ นี่คือโค้ด:
@Component({
selector: 'drawer-item',
templateUrl: '../res/views/drawer-item.html'
})
export class DrawerItemComponent
{
@Input() text:string;
@Input() icon:string;
@Input() textClass:string;
}
<div class="drawer-item-text word-wrap {{textClass}}"> {{text}}</div>
<i class="mdi mdi-{{icon}} drawer-item-img"></i>
ฉันใช้มันแบบนี้:
<drawer-item (click)="selectCompany()" [text]="selectedCompanyLabel" [icon]="selectedCompanyIcon" [textClass]="selectedCompanyClass"></drawer-item>
อย่างที่คุณเห็นฉันกำลังผูกข้อความกับตัวแปร ตัวอย่างเช่นกับ selectedCompanyLabel ด้วยวิธีนี้ทุกอย่างทำงานได้ดี และถ้า selectedCompanyLabel เปลี่ยน ป้ายก็จะเปลี่ยนตามด้วย
ฉันจะหลีกเลี่ยงตัวแปรนั้นโดยใช้บางอย่างเช่น:
[text]="company ? 'company.name' : 'Select a company'"
แต่ถ้าเป็นแบบนี้ เนื้อหาจะไม่ถูกผูก ดังนั้นถ้า บริษัท เปลี่ยน ป้ายกำกับจะไม่ถูกอัปเดต
แต่ถ้าฉันใช้กลยุทธ์นั้นในสไตล์ มันได้ผล! ตัวอย่างเช่นอะไรบางอย่างแบบนี้ ทำงานได้ดี:
<div class="company ? 'italic' : 'bold'"> ... </div>
คุณรู้ไหมว่าทำไม?
ขอบคุณมาก
คำตอบ #1
ฉันจะใช้สิ่งต่อไปนี้แทน:
[text]="company ? company.name : 'Select a company'"
ไม่มีเครื่องหมายอัญประกาศสำหรับ company.name
คำตอบ #2
ไม่แน่ใจว่าจากคำถามของคุณปัญหาคืออะไร แต่ฉันเดาว่านี่คือสิ่งที่คุณกำลังมองหา
[text]="company?.name"
