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

javascript - การใช้ ngx-toastr ทั่วทั้งแอปพลิเคชัน Angular


ฉันกำลังใช้การใช้งาน toastr ดังต่อไปนี้ในแอป Angular 7 ของฉัน: https://www.npmjs.com/package/ngx-toastr

ฉันกำลังพยายามหาวิธีว่าฉันสามารถทำให้โทสต์ทั้งหมดแนบไปกับ body หรือองค์ประกอบ div อื่น ๆ ซึ่งจะอยู่ในคอมโพเนนต์ root app ของฉันได้อย่างไร (ฉันต้องการให้มันแสดงอยู่แม้ในกรณีที่คอมโพเนนต์ที่เรียกใช้ถูกทำลาย)

มีวิธีใดในการเก็บถาวรมันหรือไม่?

คำตอบ #1

ตามที่ readme ในลิงก์ของคุณได้กล่าวไว้แล้ว คุณจำเป็นต้องจัดเตรียม ToastrContainer ของคุณเอง

import { 
    ToastrModule, 
    ToastContainerModule // Add this one
} from 'ngx-toastr';


@NgModule({
  declarations: [AppComponent],
  imports: [
    //...
    ToastContainerModule // Add this one
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

และเพิ่ม div ไปที่คอมโพเนนต์รากของคุณ (หรือที่ใดก็ได้ที่คุณต้องการให้คอนเทนเนอร์อยู่) ดังนี้:

@Component({
  selector: 'app-root',
  template: `
  <h1><a (click)="onClick()">Click</a></h1>
  <div toastContainer></div> <!-- Add this line here, above should be your router -->
`
})
export class AppComponent implements OnInit {
  // Get a reference to the directive
  @ViewChild(ToastContainerDirective) toastContainer: ToastContainerDirective;

  constructor(private toastrService: ToastrService) {}
  ngOnInit() {
    // Register the container
    this.toastrService.overlayContainer = this.toastContainer;
  }
  onClick() {
    this.toastrService.success('in div');
  }
}

คำตอบ #2

ประกาศโมดูลในโมดูลรากของคุณ (ปกติคือ app.module.ts)

import { ToastrModule } from 'ngx-toastr';

@NgModule({
    imports: [ ToastrModule.forRoot({ ...global options... }) ],
    ...
})

ทอสต์สามารถเรียกใช้ได้จากทุกที่ (ถ้าคุณได้ฉีดบริการในคอมโพเนนต์ของคุณแล้ว) และควรจะแสดงในตำแหน่งที่คุณได้กำหนดให้แสดง (และไม่มีองค์ประกอบใดบังพวกมัน)