javascript - angular 6 สร้างอินสแตนซ์ของ TemplateRef
ฉันมีคอมโพเนนต์ (Angular 6) และพารามิเตอร์อินพุตประเภท TemplateRef<any>
class TestComponent {
@Input() tpl: TemplateRef<any>;
...
}
ตอนนี้ฉันต้องการสร้างการทดสอบและฉันหาไม่เจอวิธีสร้างเทมเพลตในการทดสอบและตั้งค่าเป็นช่องกรอกข้อมูล
ใน HTML ของฉันฉันมีเทมเพลตแบบ
<test>
<ng-template #tpl>
<div>OLOLO</div>
</ng-template>
</test>
ฉันต้องการอะไรบางอย่างแบบนี้
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
component.template = here I need instance of TemplateRef
ขอบคุณ
คำตอบ #1
ฉันไม่เข้าใจว่าทำไมคุณถึงทำแบบนี้ แต่ถ้าคุณต้องการเข้าถึงเทมเพลตในไฟล์สเปค แทนที่จะใช้ input ให้ใช้ viewchild ในคอมโพเนนต์
ดังนั้นรหัสที่ใช้จะเป็น
class TestComponent {
@ViewChild('tpl') public tpl: ElementRef;
...
}
และในไฟล์ spec.ts ลองสิ่งนี้
it('should create', () => {
console.log(component.tpl);
expect(component).toBeTruthy();
});
