[英]how to access properties of a component inside a angular material pop up/dialog component?
我正在從我的組件打開一個對話框。
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
width: '500px',
data: DialogData
});
dialogRef.afterClosed().subscribe(result => {
this.dialogData = new DialogData('label...',this.frequency,'action','screen_ocr','parameter_type','parameter_value',0,'next_node',1,'index',false);
console.log('The dialog was closed');
});
我想從這個組件訪問幾個屬性來初始化 DialogOverviewExampleDialog
@Component({
selector: 'dialog-overview-example-dialog',
templateUrl: 'dialog-overview-example-dialog.html',
})
export class DialogOverviewExampleDialog {
//here I want to use properties of my component
constructor(private dialogService: DialogDataService,
public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
@Inject(MAT_DIALOG_DATA) public data: DialogData) {}
唯一的方法,我可以弄清楚這是使用 rxjs 的行為主題來訪問屬性,但是這個 DialogOverviewExampleDialog 是在我的組件內部聲明的。 有沒有辦法直接訪問我的組件在 DialogOverviewExampleDialog 中的屬性? 反之亦然。
謝謝,
使用這個: dialogRef.componentInstance.YOUR_PROPERTY
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
width: '500px',
data: DialogData
});
dialogRef.componentInstance.YOUR_PROPERTY
dialogRef.afterClosed().subscribe(result => {
this.dialogData = new DialogData('label...',this.frequency,'action','screen_ocr','parameter_type','parameter_value',0,'next_node',1,'index',false);
console.log('The dialog was closed');
});
你可以試試這個
component.ts我們從中打開對話框的父組件
import { Component, Inject } from '@angular/core';
import { VERSION, MatDialogRef, MatDialog, MatSnackBar, MAT_DIALOG_DATA } from '@angular/material';
import {ConfirmationDialog} from './confirm/confirmation-dialog.component';
@Component({
selector: 'material-app',
templateUrl: 'app.component.html'
})
export class AppComponent {
version = VERSION;
constructor(private dialog: MatDialog,
private snackBar: MatSnackBar) {
}
openDialog() {
const dialogRef = this.dialog.open(ConfirmationDialog,{
data:{name: 'Test1', from: 'Component'} **// passing this data to dailog**
});
const snack = this.snackBar.open('Snack bar open before dialog');
dialogRef.afterClosed().subscribe((confirmed: any) => {
console.log(confirmed); **// after modal close data you will get here which passed from dialog on onConfirmClick() function**
});
}
}
確認-dialog.component.ts
import { Component, Inject } from '@angular/core';
import { VERSION, MatDialogRef, MatDialog, MatSnackBar, MAT_DIALOG_DATA } from '@angular/material';
@Component({
selector: 'confirmation-dialog',
templateUrl: 'confirmation-dialog.html',
})
export class ConfirmationDialog {
message: string = "Are you sure?"
confirmButtonText = "Yes"
cancelButtonText = "Cancel"
constructor(
@Inject(MAT_DIALOG_DATA) private data: any,
private dialogRef: MatDialogRef<ConfirmationDialog>) {
console.log(this.data); **// Here is data recived from AppComponent.ts**
}
onConfirmClick(): void {
this.dialogRef.close({name: 'Test', from: 'Dialog'}); **// on button click data will send to parent component after dialog close * AppComponent**
}
}
許多其他解決方案的一種可能解決方案是使用 npm 包@costlydeveloper/ngx-awesome-popup 來實現。
它在不破壞對象引用的情況下提供了兩個組件之間的 2 向數據綁定,即父組件(從那里調用彈出對話框)和子組件(在對話框內調用的那個)。 子組件可以從父組件接收數據並將響應負載對象發送回。
在 app.module.ts 中,您可以僅啟用對話框模塊而無需導入其他包功能。
在您的AppModule
導入對話框模塊:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
// Import your library
import {DialogConfigModule, NgxAwesomePopupModule} from '@costlydeveloper/ngx-awesome-popup';
@NgModule({
declarations: [
AppComponent
],
imports : [
BrowserModule,
// Enable package and dialog modules
NgxAwesomePopupModule.forRoot(),
DialogConfigModule.forRoot()
//
],
providers : [],
bootstrap : [AppComponent]
})
export class AppModule {
}
ParentComponent
設置
import {Component, OnInit} from '@angular/core';
import {ChildComponent} from './child.component';
// import library classes
import {DialogLayoutDisplay, DialogInitializer, ButtonLayoutDisplay, ButtonMaker} from '@costlydeveloper/ngx-awesome-popup';
@Component({
selector : 'app-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.scss']
})
export class ParentComponent implements OnInit {
ngOnInit() {
// Call the dialog.
this.dialog();
}
// Create the method.
dialog() {
// Instance of DialogInitializer includes any valid angular component as an argument.
const dialogPopup = new DialogInitializer(ChildComponent);
// Any data can be sent to ChildComponent.
dialogPopup.setCustomData({name: 'John', surname: 'Doe', id: 1});
// Set some configuration.
dialogPopup.setConfig({
Width : '500px',
LayoutType: DialogLayoutDisplay.NONE // SUCCESS | INFO | NONE | DANGER | WARNING
});
// Set some custom buttons as list.
// SUCCESS | INFO | NONE | DANGER | WARNING | PRIMARY | SECONDARY | LINK | DARK | LIGHT
dialogPopup.setButtons([
new ButtonMaker('Edit', 'edit', ButtonLayoutDisplay.WARNING),
new ButtonMaker('Submit', 'submit', ButtonLayoutDisplay.SUCCESS),
new ButtonMaker('Cancel', 'cancel', ButtonLayoutDisplay.SECONDARY)
]);
// Simply open the popup and listen which button is clicked and,
// receive optional payload from the ChildComponent.
const subscription = dialogPopup.openDialog$().subscribe(resp => {
// This is the response from the ChildComponent it will include
your payload data and info about which button is clicked.
// your payload data from the child component is here.
console.log('payload response: ', resp.Payload);
if (resp.ClickedButtonID === 'submit') {
// do some logic
}
subscription.unsubscribe();
});
}
}
以在 Child 組件構造函數中注入 DialogBelonging 依賴項的方式設置ChildComponent
,這將為您提供操作數據和觸發各種事件(例如按鈕單擊偵聽器和關閉加載器)的選項。 要將數據發送回 ParentComponent 只需將您的對象作為參數傳遞給 close 方法,如下所示: close(someObject)
,您也可以實現簡單的邏輯來偵聽單擊哪個按鈕並發送不同的數據。 您從 ParentComponent 發送的 2 路綁定數據在那里 this.dialogBelonging.CustomData
import {Component, OnInit, OnDestroy} from '@angular/core';
import {Subscription} from 'rxjs';
import {DialogBelonging} from '@costlydeveloper/ngx-awesome-popup';
@Component({
selector: 'app-any-angular-component',
templateUrl: './any-angular.component.html',
styleUrls: ['./any-angular.component.scss']
})
export class AnyAngularComponent implements OnInit, OnDestroy{
subscriptions: Subscription[] = [];
// Dependency Injection of the dialogBelonging in the constructor is crucial.
constructor(private dialogBelonging: DialogBelonging) {}
ngOnInit(): void {
// Here is your 2 way data binded object with the Parent component.
console.log(this.dialogBelonging.CustomData);
// Subscribe to button listeners.
this.subscriptions.push(
// IDialogEventsController
this.dialogBelonging.EventsController.onButtonClick$.subscribe((_Button) => {
if (_Button.ID === 'edit') {
// Do some logic for example edit user.
} else if (_Button.ID === 'submit') {
// Do some logic and close popup.
this.dialogBelonging.EventsController.close();
}
else if (_Button.ID === 'cancel') {
// Do some logic and close popup.
this.dialogBelonging.EventsController.close();
}
})
);
}
ngOnDestroy(): void {
// Care about memory and close all subscriptions.
this.subscriptions.forEach(sub => sub.unsubscribe());
}
}
Notice: For Angular 8:
packahe 與 angular 9+ 一起使用,但由於入口組件規則從 angular 9+ 中棄用,除非您將其添加到 app.module 中的入口組件列表中,否則您將無法打開 ChildComponent .ts
entryComponents: [Childcomponent]
為什么不使用服務文件在對話組件之間進行通信並在它們之間發出數據。
這應該讓我明白我的意思=> https://www.dotnetcurry.com/angularjs/1445/angular-services-component-communication
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.