ค้นหาเว็บไซต์

typescript - Angular 6 - ซ่อนหรือแสดง Div ในคอมโพเนนต์ที่ถูกกระตุ้นจาก Service


ฉันมีบริการซึ่งมีวิธีการที่ทำบางอย่าง

service.ts:

doSomething() {
    // Does something here
}

บริการนี้สื่อสารกับส่วนประกอบด้านล่าง:

myComponent.ts

ฉันมี: myComponent.html ซึ่งมี div:

<div class="myDiv">Something Here</div>

สิ่งที่ฉันต้องการทำคือการแสดงและซ่อน div โดยใช้โค้ดในเมธอด doSomething() ของ service

แบบนี้:

doSomething() {

    1. Show myDiv   
    2. // Do something here
    3. Hide myDiv
}

ฉันจะทำสิ่งนี้ได้อย่างไร?

คำตอบ #1

โดยเฉพาะฉันแทรกเข้าไปในเมธอด doSomenthing() ชุดค่าของแฟล็กเพื่อควบคุม div

ชิ้นส่วน

doSomething() {
  service
    .doSomething()
    .subscribe(
       r => {
          this.show = true;   
          2. // Do something here
          this.show = false;  
       }
    );
}

<div *ngIf="show" class="myDiv">Something Here</div>

แต่โค้ดนี้ต้องอยู่ในคอมโพเนนต์ ไม่ใช่อยู่ในเซอร์วิส

คำตอบ #2

เพิ่มแอตทริบิวต์ ngIf ลงในมาร์กอัป:

*ngIf="IAmDoingSomething" 

ภายในส่วนประกอบคุณสามารถทำสิ่งต่อไปนี้ได้:

export class MyDoSomethingComponent{
public IAmDoingSomething = false;
...
   invokeServices = async  () => {
       this.IAmDoingSomething = true;
       await doSomething();
       this.IAmDoingSomething = false;
    }
...
}

บทความที่เกี่ยวข้อง